I tried to reduce as much as possible my piece of code to illustrate my question. So…
This code, does not “do” anything. My point is just to ask if it would be possible to get access to the method needsCasting()
without the casting in following example ?
It for sure has to do with what compiler “sees”, and what is for him the difference between CustomTreeItem
and it’s parent TreeItem<Dummy>
.
Of what my research ended up with, is that the ‘hidden’ list children inside the TreeItem
class is of TreeItem<Dummy>
, and not CustomTreeItem
, but my question stays whole :
“Is there a way to access a child method directly (without casting) ?”
Here comes the example :
import javafx.scene.control.TreeItem; import javafx.scene.control.TreeTableRow; public class CastingQuestion { public class Dummy extends TreeTableRow<Dummy> { } public final class CustomTreeItem extends TreeItem<Dummy> { private void needsCasting() { System.out.println("Hello world"); } public void listChildren() { for (TreeItem<Dummy> item : getChildren()) { ((CustomTreeItem) item).needsCasting(); } } } }
Advertisement
Answer
If you have a variable of type TreeItem<Dummy>
, you cannot access a method or property on it that is specific to CustomTreeItem
without first casting it to a CustomTreeItem
object. This is because all the compiler knows is that the variable is of type TreeItem<Dummy>
which isn’t necessarily going to be a CustomTreeItem
.
Say I had two classes, TreeItemA
and TreeItemB
– both subclasses of (extending from) TreeItem<Dummy>
. And I have a variable of type TreeItem<Dummy>
.
TreeItem<Dummy> item;
This variable could be an instance of TreeItemA
or TreeItemB
:
item = new TreeItemA(); //valid assignment item = new TreeItemB(); //valid assignment
Therefore, you can only access properties or methods of the variable that are in the base TreeItem
class if you don’t cast down to a subclass – it all depends on the type of the variable you are working with.
Edit: It is worth noting that the getChildren()
method you are calling in CustomTreeItem
returns ObservableList<TreeItem<T>>
(according to default TreeItem
implementation). This means that when you iterate over the list returned from getChildren()
, each element will be of the type TreeItem<Dummy>
.