Java Program to use Super Keyword in Inheritance Class

This is a Java Program to Use This Keyword in Inheritance Class.

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.

  1. class Base1
  2. {
  3.   int x = 19;
  4. }
  5. class Base2 extends Base1
  6. {
  7.   int x = 20;
  8. }
  9. class Child extends Base2
  10. {
  11.      int x = 21;
  12.      void show()
  13.      {
  14.         System.out.println("Child Class-"+x);
  15.         System.out.println("Base1 class-"+super.x);
  16.         System.out.println("Accessing value of data member via This Keyword");
  17.         System.out.println("Base2 class-"+(((Base1)this).x));
  18.      }
  19.     public static void main(String... a)
  20.     {
  21.        Child obj = new Child();
  23.     }
  24. }


$ javac
$ 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.


Here’s the list of Best Books in Java Programming, Data Structures and Algorithms.

If you find any mistake above, kindly email to [email protected]

Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.