我观察到这样的行为,当我们从一个多态对象调用一个变量时,它会调用父变量,但是当我们用相同的多态对象调用一个方法时,它会调用子方法。为什么这是 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
最佳答案
首先要记住你的变量不是多态的
,下一个高潮就是你的this点
Parent parentChildOne = new ChildOne();
Parent parentChildTwo = new ChildTwo();
看看当您尝试使用 Parent parentChildOne
调用方法时,它应该调用子方法,因为它已被覆盖,并且根据多态性应该调用它。
现在再次看到 Parent parentChildOne
变量的相同对象,现在这里没有多态性但 jvm 现在正在处理它 shadowing
的概念br/>所以这就是为什么他们都表现出他们的真实行为
请按照shadowing in java的教程进行操作
关于java - 多态中的变量绑定(bind) VS 方法绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16273759/