In multi level inheritance we can only call the data member of parent class from child class via Super keyword but we cannot call the data member of grand parent class from child class. We can achieve this via This keyword. Here we are doing the same to print the value of X of grand parent class from child class.
Here is the source code of the Java Program to Use This Keyword in Inheritance Class. The Java program is successfully compiled and run on a Windows system. The program output is also shown below.
int x = 19;
class Base2 extends Base1
int x = 20;
class Child extends Base2
int x = 21;
System.out.println("Accessing value of data member via This Keyword");
public static void main(String... a)
Child obj = new Child();
$ javac Child.java $ java Child Child Class-21 Base1 class-20 Accessing value of data member via This Keyword Base2 class-19
Sanfoundry Global Education & Learning Series – 1000 Java Programs.