I am trying to extend class which has a variable that I also need to be extended. Is there a "good" way of achieving this?
I have extended parent class and a variable that is in the parent class. Now I need to use extended variable in child class. Here is pseudo-code:
public class Parent {
private ParentVariable variableToUse;
//getters, setters
}
public class ParentVariable {
//some fields
}
public class ChildVariable extends ParentVariable {
//more fields
}
public class Child extends Parent {
private ChildVariable variableToUse;
//getters, setters
}
How should I override "variableToUse"
so that every-time I try to access this variable from "Child"
I would access "ChildVariable"
instead of "ParentVariable"
?
You will be effectively hiding the parent variable here by including "variableToUse" in the child class.
As variableToUse is of the type ParentVariable anyway, i suggest you leave it out of the ChildClass altogether, and use a getter which ensures type. Eg -
public class Child extends Parent {
//private ChildVariable variableToUse; -> remove this
private ChildVariable checkAndGetChildVariable() {
if(variableToUse instanceof ChildVariable) {
return (ChildVariable)variableToUse;
}
return null;//Or throw exception
}
}
For further clarity, ensure this in the constructor
public class Child extends Parent {
//private ChildVariable variableToUse; -> remove this
public Child(ParentVariable variable) {
super(checkChildVariable(variable));
}
private static ChildVariable checkChildVariable(ParentVariable variable) {
if(variable instanceof ChildVariable) {
return (ChildVariable)variable;
}
throw UnsupportedOperation("invalid type");
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.