Search code examples
javadynamic-dispatch

Why value of parent class is variable is shown as output


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

`

Solution

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

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