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.
class Base1
{
int x = 19;
}
class Base2 extends Base1
{
int x = 20;
}
class Child extends Base2
{
int x = 21;
void show()
{
System.out.println("Child Class-"+x);
System.out.println("Base2 class-"+super.x);
System.out.println("Accessing value of data member via This Keyword");
System.out.println("Base1 class-"+(((Base1)this).x));
}
public static void main(String... a)
{
Child obj = new Child();
obj.show();
}
}
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.
Related Posts:
- Apply for Java Internship
- Practice BCA MCQs
- Practice Information Technology MCQs
- Practice Programming MCQs
- Apply for Computer Science Internship