Issue
public class CustomNode extends GuiObject {
public void doSomethingWithBase() {
Pane base = getBase();
//The problem is here, base can only be VBox or HBox, but
//accessing it as a Pane removes a couple of needed features like
//setFillHeight(boolean val), etc
//I can do casting here (to VBox or HBox), but it doesn't look too elegant
//Any alternatives?
}
}
public abstract class GuiObject {
private final Pane base;
public Pane getBase() {
return base;
}
}
In doSomethingWithBase()
I need to process base which can only be VBox
or HBox
, but I'm forced to use a superclass to get it, but also I'm forced to do casting, which I don't prefer.
Is there any alternative to casting here?
Solution
If you only have HBox or VBox in doSomethingWithBase you can use generics. Would look like this:
public class CustomNode extends GuiObject<VBox> {
public void doSomethingWithBase() {
VBox base = getBase();
//The problem is here, base can only be VBox or HBox, but
//accessing it as a Pane removes a couple of needed features like
//setFillHeight(boolean val), etc
//I can do casting here (to VBox or HBox), but it doesn't look too elegant
//Any alternatives?
}
}
public abstract class GuiObject<P extends Pane> {
private final P base;
public P getBase() {
return base;
}
}
If you have both VBox and HBox in doSomethingWithBase then the question is - how do you know what you get?
Answered By - TomStroemer