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)//The output is 12. (The value of parent class member data)

I would like to know how they are different.


Variables bind to the reference, not to the object created. In your example, A a = new B(); Here a is a reference to which variable binds of type A . And, created object is of type B , to which methods are bind. That's why it is picking values for variables of references. This is called data hiding. Because when we create same variable in sub-class, value of variable of sub-class is hidden under super class variable. Hope it helps.


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.

链接地址: http://www.djcxy.com/p/59524.html

上一篇: PHP:{$ foo}和$ {foo}之间是否有区别

下一篇: 给定数据类型效果如何覆盖成员变量