3

As I can understand here 'a1' reffed to a class B object which has 'a=200' as an attribute. Therefore I expected program will print 200. But why does this program prints 100 instead of 200?

    class A{
        int a=100;
    }

    class B extends A{
        int a=200;

    }

    class Demo{
        public static void main(String args[]){
            A a1=new B(); 
            System.out.println("a : "+a1.a); //Prints 100  
        }
    }
4

2 回答 2

9

By declaring a field in class B that has the same name as a field in its parent class A, you are essentially hiding that field. However, field access on a variable is done based on that variable's declared/static type.

In other words, fields are not polymorphic entities like methods are.

In this case, the variable a1 is declared as type A. The field accessed will therefore be the one in the parent class, A.

于 2013-09-17T14:56:12.480 回答
4

Docs saying

Within a class, a field that has the same name as a field in the superclass hides the superclass's field, even if their types are different. Within the subclass, the field in the superclass cannot be referenced by its simple name. Instead, the field must be accessed through super

So in your case the field a of class B hidden by the super calss A

If you want to get the value,

class Demo{
    public static void main(String args[]){
        A a1=new B(); 
        System.out.println("a : "+a1.a); //Prints 200  
    }
}
class A{
    int a=100;
}

class B extends A{
     public B() {
        super.a=200;
    }

}
于 2013-09-17T14:55:33.627 回答