0

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?

`
    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);
        }
    }

`
4

1 回答 1

-1

变量不能在 Java 中被覆盖,看看这个另一个问题:

为什么超类的实例变量在子类方法中没有被覆盖

于 2017-08-03T17:37:47.177 回答