I do not understand why the output of this code is 10
:
package uno;
public class A
{
int x = 10;
A(){int x = 12; new B();}
public static void main(String args[]){
int x = 11;
new A();
}
class B{
B(){System.out.println(x);}
}
}
How does the scope in this example work? Why System.out.println(x);
prints 10? Is it because the instruction System.out.println(x);
is outside the parentesis of the costructor: A(){int x=12; new B();}
and so int x = 12
lives only there but when System.out.println(x);
is invoked, x = 12
lives no longer?? So the first x
is x=10
declared in class A
? What if there were any x
in class A
? Would it print 11
?