Nested Classes
public class Nesting
{
    public static void main(String args[])
    {
        B.C obj= null;
        obj=new B().new C();
    }
}
class A
{
    int val;
    A(int v)
    {
    val=v;
    }
}
class B extends A
{
    int val=1;
    B()
    {
        super(2);
    }
 
    class C extends A
    {
        int val=3;
        C()
        {
            super(4);
            System.out.println(B.this.val);
            System.out.println(C.this.val);
            System.out.println(super.val);
            /* =======================
            //look at this statement carefully! */
            System.out.println(B.super.val);
        }
    }
}

The explanation and with a superb hint is here:

/*
=========
Question
=========
"from Khalid Mughal pg no:301"
 
Could you please explain how the ans got as 1,3,4 inthis order?
 
=========
Answer
========
1. First new B(), this calls the B class constructor, this calls the super(2) first.
2. This super(2) assign the variable val as 2. This is A class val variable.
3. Now the instance variable of B class assignment happens, this assign the val variable of B class with 1
4. At this point, the B class has two val variable access, one with class A value(2) and other with class B value(1).
5. After this on the B class object we are calling the nested class C class object.
6. In the constructor of C class we are calling first super(4), as the super class is A, the val variable for A is again assigned to value 4.The B class val is still 1 and B class’s A class val value is still 2 and still accessible.
7. Finally we assign the val variable in C class as 3
8. So first we are printing the B class variable 1
9. Then C class local variable 3
10. Then we have used the super which is A class variable for C, that is 4.
-----------------------------------------------------------------------
  VERY IMPORTANT (this decoration added by Raghs!)
-----------------------------------------------------------------------
11. Add one other statement
a. System.out.println(B.super.val);
 
It will give that hidden 2 value for B class’s A class val variable.
--------------------------------------------------------------------------
*/
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-Share Alike 2.5 License.