I have a class A with a variable bool var = true and a getter method getVar().
I’m trying to create a class B that extends A and redefines var to bool var = false. The code:
public class A{
protected boolean var = true;
public boolean getVar(){
return var;
}
}
public class B extends A{
protected boolean var = false;
}
The problem is that if I execute:
B b_class = new B();
System.out.println(b_class.getVar());
I obtain true and I don’t undestand why. What I’m doing wrong?
You shouldn’t be creating a new instance variable in your overridden class, because it can’t be seen by the super class (A), and therefore when
getVar()is called, it will return the value it can see. You should instead be setting the value ofvarin the constructor to be what you want.