开发者

Simple Java "New" concept question

The compiler shows an error at new Stock[2]; after ;{ expect.

public class TestStockUI {
    Stock[] stock = new Stock[2];
    stock[0] = new Stock("Microsoft", "MSFT", 15.69);
    stock[1] = new Stock("Google", "GOGL", 32开发者_如何转开发3.98);

    public TestStockUI() { }

}

Then I have changed it like below resulting in the same error.

public class TestStockUI {
    Stock[] stock = new Stock[2];
    stock[0] = new Stock("Microsoft", "MSFT", 15.69);
    stock[1] = new Stock("Google", "GOGL", 323.98);

}

This solve the problem but I don't know why.

public class TestStockUI {
    Stock[] stock = new Stock[2];
    {
        stock[0]=new Stock("Microsoft","MSFT",15.69);
        stock[1]=new Stock("Google","GOGL",323.98);
    }

}


{
    stock[0]=new Stock("Microsoft","MSFT",15.69);
    stock[1]=new Stock("Google","GOGL",323.98);
}

This creates an initialization block, where these statements are legal. They are not legal in the first two examples.


You can't execute code in the class definition body.

You have to either declare attributes or method. Additionally ( as in your case ) you can create free floating blocks where you can execute code, that's why the first two didn't work but the third did.

class A { 
   private int i;
   i = 10; // illegal
}

class A { 
   private int i;
   { i = 10; } // ok, free floating code
}

The free floating block of code will be executed when the instance is created. Most of the times this is unneeded because that kind of initialization goes better in the class constructor.

If used with static modifier it will be executed when the class is loaded.

One common use of it is for anonymous classes as a substitute for constructor, for instance in Swing, this is somewhat common when building prototypes.

JPanel p = new JPanel(){{ //<-- free floating code aka double initialization idiom.
    add( new JLabel("A"));
    add( new JLabel("B"));
}};


As mentioned already, the initializations are not valid outside a method construct or outside a block as this violates the programming syntax. Pls do refer to any good java book.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜