Reputation: 83
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 toT
, but with that instance viewed as an instance of the superclass ofT
.
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
Upvotes: 6
Views: 167
Reputation: 280181
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
Upvotes: 2