Understanding the concept of inheritance in Java
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 givin开发者_如何学Cg 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....
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.
index is simply a field belonging to the parent class. Because it belongs to the parent class, it means that it's an attribute to all the children. To simply the concept:
A Class Animal could have a field age and a field name All sub classes would share those attributes, but would have additional field(s), which would be contained into those children classes only. For example hairColour could be the only attribute of the Dog class, but not to the class Snake, which could have a simple unique attribute venomous
In this structure all Animal have a name, and an age, which is what could define Animals in general, an each specie have some extra attribute(s) unique to them, which are contained into their respective sub classes.
Your code doesn't clearly show this, as your sub class has no constructor, indeed no super constructor call. As explained by Petar, your none private attribute index is access from the super class
This happens coz functions follows runtime binding whereas variables are bound at compile time.
So the variables depend on the reference's datatype whereas the functions depend on the value represent by the reference's datatype.
When we assigning the object of sub class to parent class object only the common property both class can be accepted by the parent class object , is called as object slicing that's why the value of patent class 5 is printed its only happen with property not a method
精彩评论