开发者

Can we access the objects outside the method?

I created two Classes A and B.

I created an object in B outside any method like below, but I can't acc开发者_运维百科ess variables and methods from A. Why? I can't understand this

Class B {
    int a, b;
    A Obja = new(); // this does not work

    public void method1() {
        A Obja1 = new A(); // from here I am able to access the members from A
    }
}


You forgot to specify the classname for the new keyword.

A Obja = new A();

See also:

  • Java tutorial - Creating objects

This would however have resulted in a compilation error, not a runtime error. So if your code actually compiled, then your concrete problem might rather be a scoping or visibility issue. But the code example given as far doesn't indicate any.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜