理解Java中的继承概念 [英] Understanding the concept of inheritance in Java
问题描述
我只是刷新了java的oops功能。所以,我对继承概念有点困惑。为此,我有以下示例代码:
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();
}
}
现在上面的代码输出为: 5,Sub。
Now above code is giving me output as : 5,Sub.
这里,我们重写了printVal()方法,因此可以理解它只是访问子类方法。
Here, we are overriding printVal() method, so that is understandable that it is accessing child class method only.
但是我无法理解为什么它从超级类中访问x的值...
But I could not understand why it's accessing the value of x from Super class...
提前致谢... ..
Thanks in advance....
推荐答案
对象有类型,变量有类型。因为你把:
Objects have types, and variables have types. Because you put:
Super sup = new Sub();
现在你有一个变量 sup
的类型超级
,指的是 Sub
类型的对象。
Now you have a variable sup
of type Super
which refers to an object of type Sub
.
当您在对象上调用方法时,将根据对象的类型选择运行的方法,这就是它打印Sub而不是Super的原因。
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".
当您访问对象中的字段时,将根据变量的类型选择字段,这就是您获得5的原因。
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.
这篇关于理解Java中的继承概念的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!