0
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?

1 Answers1

2

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?

TomStroemer
  • 1,390
  • 8
  • 28
  • Btw. Is `P` in `

    ` correct naming? Can you please send me a source?

    – ImNotARobot Jun 08 '20 at 13:06
  • 1
    Well, dependens on what naming conventions you use. For a discussion about this read here: https://stackoverflow.com/questions/2900881/generic-type-parameter-naming-convention-for-java-with-multiple-chars – TomStroemer Jun 08 '20 at 13:12
  • @TomStroemer Thank you for useful link, I'd rather stay with `T` though – ImNotARobot Jun 08 '20 at 13:17