开发者

Can we access the objects outside the method?

开发者 https://www.devze.com 2023-02-06 16:28 出处:网络
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

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

精彩评论

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