Coders Packet

Inheritance Hierarchy and Enclosing Context in Java

By Rakesh Jat

In Java Inner classes can extend other classes, and vice versa. An inherited field (or method) in an inner subclass can hide a field (or method) with the same name in the enclosing context.

The Inner classes can extend other classes. An inherited method in an inner subclass can hide a method with the same name in the enclosing context. The below example illustrates the situation outlined earlier. The standard form of this reference is used to access the inherited member. The keyword super would be another alternative. To access the member from the enclosing context, the special form of this reference together with the enclosing class name is used.

Inheritance Hierarchy and Enclosing Context
class Superclass {
protected double x = 3.0e+8;
}

class TopLevelClass { // Top-level Class
private double x = 3.14;
class Inner extends Superclass { // (Non-static member Class
public void printHidden() { 
//  x from superclass:
System.out.println("this.x: " + this.x);
// x from enclosing context:
System.out.println("TopLevelClass.this.x: " + TopLevelClass.this.x);
}
} // Inner
} // TopLevelClass


public static void main(String[] args) {
TopLevelClass.Inner ref = new TopLevelClass().new Inner();

ref.printHidden();
}
}

 


Output from the program:
this.x: 3.0E8
TopLevelClass.this.x: 3.14

Download project

Reviews Report

Submitted by Rakesh Jat (techraka)

Download packets of source code on Coders Packet