How the Given Data type effect Overriding member variables

I have studied some of the related posts about this topic and I have learned that when we make a variable of the same name in a subclass, that’s called hiding.


    class A {
        int i = 10;

        public void printValue() {
            System.out.print("Value-A");
            System.out.println(i);
        }
    }

    class B extends A {
        int i = 12;

        public void printValue() {
            System.out.print("Value-B");
            System.out.println(i);
        }
    }

    public class Test {
        public static void main(String args[]) {
            A a = new B();
            a.printValue();
            System.out.print(a.i);
        }
    }

When I instantiate class B with type A and print member data
A a=new B();
System.out.println(a.i)
The output is 10.(The value of parent class member data).

But when I instantiate class B as type B,
B a=new B();
System.out.println(a.i) is 12. (The value of parent class member data)

I would like to know how they are different.

Polymorphism applies only on methods. Variables still binds to the type. You can’t ovveride variables. That is the reason you are seeing different output when you changing the type.

In simple words, when you write

 A a=new B();

Just to remember, variables bind to left side and methods gets execute from right side.