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.
精彩评论