Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding the use of Super to access Superclass members

Tags:

java

super

I was referring to the java language specification to understand the use of super. While I understand the first use case i.e.

The form super.Identifier refers to the field named Identifier of the current object, but with the current object viewed as an instance of the superclass of the current class.

I can't seem to understand the following use case:

The form T.super.Identifier refers to the field named Identifier of the lexically enclosing instance corresponding to T, but with that instance viewed as an instance of the superclass of T.

Could someone please explain this with the help of code?

I suppose the following could be illustrative of the second case:

class S{
    int x=0;
}

class T extends S{
    int x=1;
    class C{
        int x=2;
        void print(){

            System.out.println(this.x);
            System.out.println(T.this.x);
            System.out.println(T.super.x);
        }
    }
    public static void main(String args[]){
        T t=new T();
        C c=t.new C();
        c.print();
    }
}

output: 2 1 0

like image 945
kharesp Avatar asked Sep 21 '13 15:09

kharesp


1 Answers

I believe it applies to this situation

public class Main {
    static class Child extends Parent{
        class DeeplyNested {
            public void method() {
                Child.super.overriden();
            }
        }

        public void overriden() {
            System.out.println("child");
        }
    }
    static class Parent {
        public void overriden() {
            System.out.println("parent");
        }
    }
    public static void main(String args[]) {
        Child child = new Child();
        DeeplyNested deep = child.new DeeplyNested();
        deep.method();
    }
}

In the JLS

The form T.super.Identifier refers to the field named Identifier of the lexically enclosing instance corresponding to T, but with that instance viewed as an instance of the superclass of T.

Identifier is overriden, the method.

Here, the lexically enclosing instance is of type Child and its superclass is Parent. So T.super refers to the instance of Child viewed as Parent.

The code above prints

parent
like image 165
Sotirios Delimanolis Avatar answered Oct 27 '22 17:10

Sotirios Delimanolis