Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoid casting in inherited java-classes

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

like image 687
t777 Avatar asked Sep 30 '13 11:09

t777


People also ask

How do you stop casting in Java?

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.

Can you cast a class in Java?

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.


1 Answers

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

like image 101
nd. Avatar answered Oct 21 '22 19:10

nd.