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)//The output is 12. (The value of parent class member data)
I would like to know how they are different.