I have 2 classes:
public class Increase {
public int a=3;
public void add(){
a+=5;
System.out.println(\"f\");
}
}
class SubIncrease extends Increase{
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.