我观察到当我们从多态对象调用变量然后调用父变量时的行为,但是当我们调用具有相同多态对象的方法时,它会调用child的方法.为什么这是
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
最佳答案 首先要记住,你的变量不是多态的,下一个高潮就是你的观点
Parent parentChildOne = new ChildOne();
Parent parentChildTwo = new ChildTwo();
当你尝试使用Parent parentChildOne调用方法时,它应该调用子方法,因为它被覆盖并且根据多态性它应该被调用.现在再次看到父parentChildOne变量的相同对象,现在这里没有多态,但jvm现在用shadowingSo的概念处理它,这就是为什么它们都显示它们的真实行为请遵循shadowing in java的本教程