I am preparing for SCJP and I got confused while reading about nested types. There is a simple question and I am not able to understand the result.
public class Outer {
private int innerCounter;
class Inner {
Inner() {
innerCounter++;
}
public String toString() {
return String.valueOf(innerCounter);
}
}
private void multiply() {
Inner inner = new Inner();
this.new Inner();
System.out.print(inner);
inner = new Outer().new Inner();
System.out.println(inner);
}
public static void main(String[] args) {
new Outer().multiply();
}
}
It prints
21
Knowing that the counter is not static, how are the first two objects considered as one object?
A non-static inner class has access to all of the members of its outer class. It’s like it was really defined as:
So let me annotate your method: