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("Base2 class-"+super.x);
  16.         System.out.println("Accessing value of data member via This Keyword");
  17.         System.out.println("Base1 class-"+(((Base1)this).x));
  18.      }
  19.     public static void main(String... a)
  20.     {
  21.        Child obj = new Child();
  22.         obj.show();
  23.     }
  24. }

Output:

$ javac Child.java
$ java Child
 
Child Class-21
Base2 class-20
Accessing value of data member via This Keyword
Base1 class-19

Sanfoundry Global Education & Learning Series – 1000 Java Programs.

advertisement
advertisement

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

advertisement
advertisement
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.