I am just refreshing the oops features of the java. So, I have a little confusion regarding inheritance concept. For that I have a following sample code :
class Super{
int index = 5;
public void printVal(){
System.out.println("Super");
}
}
class Sub extends Super{
int index = 2;
public void printVal(){
System.out.println("Sub");
}
}
public class Runner {
public static void main(String args[]){
Super sup = new Sub();
System.out.println(sup.index+",");
sup.printVal();
}
}
Now above code is giving me output as : 5,Sub.
Here, we are overriding printVal() method, so that is understandable that it is accessing child class method only.
But I could not understand why it's accessing the value of x from Super class...
Thanks in advance....
Inheritance is an important pillar of OOP(Object-Oriented Programming). It is the mechanism in java by which one class is allowed to inherit the features(fields and methods) of another class. In Java, inheritance means creating new classes based on existing ones.
Inheritance is the process by which genetic information is passed on from parent to child. This is why members of the same family tend to have similar characteristics.
Types of Inheritance in Java: Single, Multiple, Multilevel & Hybrid.
This is called instance variable hiding - link. Basically you have two separate variables and since the type of the reference is Super
it will use the index
variable from Super
.
Objects have types, and variables have types. Because you put:
Super sup = new Sub();
Now you have a variable sup
of type Super
which refers to an object of type Sub
.
When you call a method on an object, the method that runs is chosen based on the type of the object, which is why it prints "Sub" instead of "Super".
When you access a field in an object, the field is chosen based on the type of the variable, which is why you get 5.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With