I have a class:
class MyClass {
public MyClass getParent() { ... }
public MyClass[] getChildren() { ... }
....
}
and a subclass
MySubClass extends MyClass {
public String getId() { }
...
}
Everytime I used getChildren()
or getParent()
on an instance of MySubClass
, I have to cast the result of theese methods, e.g.:
MySubClass sub = new MySubClass();
((MySubClass)sub.getParent()).getId();
Is there any way (by language or design) to avoid that casting?
Thanks for any ideas!
Update
What I would like is that getParent()
and getChildren()
always return the type of the instance they are called from, e.g. sub.getChildren()
should return MySubClass[]
Add the method getId to the super class as well ie. MyClass. Any subclasses can still override and have their own implementation. If you are scared of subclasses not overriding getId,then throw an exception from the super class from getId.
The cast() method of java. lang. Class class is used to cast the specified object to the object of this class. The method returns the object after casting in the form of an object.
Beginning with Java 5.0, you can override methods with covariant return types, i.e. you can override a method to return a subclass parent class. (see Covariant return type in Java):
public class MySubClass extends MyClass {
@Override
public MySubClass getParent() {
return (MySubClass) super.getParent();
}
@Override
public MySubClass[] getChildren() {
return (MySubClass[]) super.getChildren();
}
public String getId() {
...
}
}
You can then call new MySubClass().getChildren()[0].getId()
.
Of course this will only work if MySubClass
always has MySubClass instances as parent and/or children
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With