I have a class:
class MyClass {
public MyClass getParent() { ... }
public MyClass[] getChildren() { ... }
....
}
and a subclass
You can use the self-type pattern:
class MyClass> {
public T getParent() { ... }
public List getChildren() { ... } // you can use an array here too, but don't :)
}
class MySubclass extends MyClass {
public String getId() { ... }
}
You can implement your getParent
and getChildren
methods as desired, declare fields in MyClass
that hold T
references and know that they behave at least as MyClass
references, et cetera. And if you call getParent
or getChildren
on a MySubClass
, you can use the return values as MySubClass
instances with no casts anywhere.
The primary disadvantage of this approach is that people who haven't seen it before tend to get pretty confused.