Avoid throwing in inherited java-classes

advertisements

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[]


You can use the self-type pattern:

class MyClass<T extends MyClass<T>> {
  public T getParent() { ... }
  public List<T> getChildren() { ... }  // you can use an array here too, but don't :)
}

class MySubclass extends MyClass<MySubclass> {
  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.