我观察到这样一种行为,当我们从多态对象调用一个变量时,它调用了父对象的变量,但是当我们用相同的多态对象调用一个方法时,它调用了子对象的method.Why,这就是Java语言中的多态性行为吗?为什么Java不以同样的方式处理多态变量和方法呢?
class Parent{
int age =10;
public void showAge(){
System.out.println("Parent Age:"+age);
}
}
class ChildOne extends Parent{
int age = 20;
public void showAge(){
System.out.println("child one age:"+age);
}
}
class ChildTwo extends Parent{
int age = 30;
public void showAge(){
System.out.println("Child Two Age:"+age);
}
}
public class Test{
public static void main(String[] args) {
Parent parentChildOne = new ChildOne();
System.out.println("parentChildOne.age: "+parentChildOne.age);
parentChildOne.showAge();
Parent parentChildTwo = new ChildTwo();
System.out.println("parentChildTwo.age: "+parentChildTwo.age);
parentChildTwo.showAge();
}
}下面是输出:
parentChildOne.age: 10
child one age:20
parentChildTwo.age: 10
Child Two Age:30发布于 2013-04-29 16:06:06
首先,请记住,Your variables are not polymorphic和下一个高潮是您的这一点
Parent parentChildOne = new ChildOne();
Parent parentChildTwo = new ChildTwo();请看,当您尝试使用Parent parentChildOne调用方法时,它应该调用子对象的方法,因为它被覆盖了,并且根据多态性应该调用它。
现在再次看到变量的Parent parentChildOne相同的对象,这里没有多态性,但是jvm现在用shadowing的概念来处理它。
这就是为什么他们都表现出自己的真实行为。
请按照以下shadowing in java教程进行操作
发布于 2013-04-29 15:59:33
变量在Java中不是多态的。
相反,子类中的实例变量会隐藏父类中具有相同名称的实例变量。另请参阅Can parent and child class in Java have same instance variable?
发布于 2013-04-29 15:59:35
parentChildOne和parentChildTwo属于Parent类型。因此,您打印的是Parent的age。showAge()方法也是如此,但是age的值被子类遮蔽。
https://stackoverflow.com/questions/16273759
复制相似问题