4

我观察到当我们从多态对象调用变量然后它调用父变量但是当我们调用具有相同多态对象的方法时它调用子方法的行为。为什么这是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
4

4 回答 4

1

首先要记住,Your variables are not polymorphic下一个高潮就是你的这一点

  Parent parentChildOne = new ChildOne();
  Parent parentChildTwo = new ChildTwo();

看看当你试图调用一个方法时,Parent parentChildOne它应该调用孩子的方法,因为它被覆盖并且根据多态性它应该被调用。

现在再次看到Parent parentChildOne变量的同一个对象,现在这里没有多态性,但 jvm 现在正在处理它的概念shadowing
所以这就是为什么他们都表现出他们的真实行为
请按照这个java 中的阴影教程

于 2013-04-29T08:06:06.363 回答
1

Java中的变量不是多态的。

相反,子类中 的实例变量会影响父类中同名的实例变量另请参阅Java中的父类和子类可以具有相同的实例变量吗?

于 2013-04-29T07:59:32.573 回答
0

请看评论,

class Parent{

    int age =10;

    public void showAge(){

        System.out.println("Parent Age:"+age);
    }
}

class ChildOne extends Parent{
    //when you extends Parent the inherited members are like
    //and initialized into the default constructor
    // int super.age =10; 
    int age = 20;

    public void showAge(){

        System.out.println("child one age:"+age);
    }
}

class ChildTwo extends Parent{
    //when you extends Parent the inherited members are like
    //and initialized into the default constructor
    // int super.age =10; 
    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();
            // when we call like this, goes to the parent type of the variable instead of object. 
        System.out.println("parentChildOne.age: "+parentChildOne.age);
        parentChildOne.showAge();

        Parent parentChildTwo = new ChildTwo();
            // when we call like this, goes to the parent type of the variable instead of object. 
        System.out.println("parentChildTwo.age: "+parentChildTwo.age);
        parentChildTwo.showAge();

    }
}
于 2013-04-29T08:20:13.620 回答
0

parentChildOne并且parentChildTwo是 类型Parent。所以你正在打印age. Parent该方法也有同样的情况,showAge()但子类的值age被遮蔽了。

于 2013-04-29T07:59:34.580 回答