为什么父类的值是可变的显示为输出[重复]

时间:2022-09-23 14:00:19

This question already has an answer here:

这个问题在这里已有答案:

I am new to java and was reading about dynamic dispatching. I tried its program but the output that I got was unexpected. So in the following code I made two classes one Parent and another Child and in the Child class I made object of Child class and refer it by the variable of type Parent class. When I used the that variable to print the value of i(int type instance variable of both class) I got the value of parent class but it should print value of i that is in the child class. Can anybody please clear this up?

我是java新手,正在阅读有关动态调度的内容。我尝试了它的程序,但我得到的输出是出乎意料的。因此,在下面的代码中,我创建了两个类,一个Parent和另一个Child,在Child类中,我创建了Child类的对象,并通过Parent类的变量引用它。当我使用该变量来打印i的值(两个类的int类型实例变量)时,我得到了父类的值,但是它应该打印子类中的i的值。任何人都可以清楚这一点吗?

`
    class Parent 
    {
        int i=10;
    }
    class Child extends Parent
    {
        int i=20;
        public static void main(String ar[])
        {
            Parent obj= new Child();
            System.out.println(obj.i);
        }
    }

`

1 个解决方案

#1


-1  

Variables can't be overriden in Java, take a look at this other question:

在Java中无法覆盖变量,看看这个其他问题:

why instance variable of super class is not overridden in sub class method

为什么超类的实例变量没有在子类方法中重写

#1


-1  

Variables can't be overriden in Java, take a look at this other question:

在Java中无法覆盖变量,看看这个其他问题:

why instance variable of super class is not overridden in sub class method

为什么超类的实例变量没有在子类方法中重写