0

I have two classes (A and B) and B extends A.

public class A {
   protected int i = 1;
}

public class B extends A{
   protected int i = 2;
}

In this case the program writes 1.

A a = new B();
System.out.println(a.i); //1

But if I assign value i in the constructor it writes 2.

public class B extends A{
   public B(){
      i=2;
   }
}

A a = new B();
System.out.println(a.i); //2

Why?

user2693979
  • 2,482
  • 4
  • 24
  • 23

1 Answers1

2

From the official doc:

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, which is covered in the next section. Generally speaking, we don't recommend hiding fields as it makes code difficult to read.

Fields aren't polymorphic, and you keep a reference on a A object. By executing i = 2, you change the value of the field, hence the result modified.

Related question: Hiding Fields in Java Inheritance

Community
  • 1
  • 1
Maxime Lorant
  • 34,607
  • 19
  • 87
  • 97