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  
        }
    }
3
  • 5
    Polymorphism and late binding doesn't apply to fields. Commented Sep 17, 2013 at 14:52
  • 5
    Fields are not overridden. They are hidden. Commented Sep 17, 2013 at 14:53
  • u can't override class instance. a1 is declare type A so for class instance its go for A class. Commented Sep 17, 2013 at 15:07

2 Answers 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.

Sign up to request clarification or add additional context in comments.

4 Comments

is it call hiding or shadowing??
@nachokk from the JLS on Shadowing: Some declarations may be shadowed in part of their scope by another declaration of the same name, in which case a simple name cannot be used to refer to the declared entity.
mm so in B it's shadow a ? cause if they are in the same package A.a is in part of the scope or im confused?
@nachokk In this scenario it's hiding. The declared B.a is hiding the A.a. If you had a static field called c and a static method in the same class that declared a local variable c, that c would shadow the static c.
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;
    }

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.