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?
In Java, fields are not overridden, they are hidden. That means
Increase.aandSubIncrease.aare separate fields that can be changed and queried separately. Because the type of your variablefisIncrease, the expressionf.areturns the value of the superclass field. But theadd()method is overridden andf.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.