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

`
Scath
  • 3,777
  • 10
  • 29
  • 40

1 Answers1

-1

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

rastadrian
  • 1,025
  • 1
  • 10
  • 17