Reputation: 752
I have 2 classes:
public class Increase {
public int a=3;
public void add(){
a+=5;
System.out.println("f");
}
}
class SubIncrease extends Increase{
public int a=8;
public void add(){
a+=5;
System.out.println("b" + a);
}
}
But when I run
Increase f=new SubIncrease();
System.out.println(f.a);
f.add();
System.out.println(f.a);
I got this output:
3
b13
3
Could anyone help me to understand why this happens? The value of the a attribute was changed in method add, as shown by the second outpuy row...why does it get back to its original value?
Upvotes: 1
Views: 961
Reputation: 346317
In Java, fields are not overridden, they are hidden. That means Increase.a
and SubIncrease.a
are separate fields that can be changed and queried separately. Because the type of your variable f
is Increase
, the expression f.a
returns the value of the superclass field. But the add()
method is overridden and f.add()
calls the subclass method, which modifies the subclass field.
Hiding a field rarely makes sense, so you should avoid it. If you want to have a field with a different default value in a subclass, define it only in the superclass and assign a value to it in the subclass constructor.
Upvotes: 5