Avoid casting in inherited java-classes

前端 未结 7 1962
执念已碎
执念已碎 2021-02-14 17:56

I have a class:

class MyClass {

  public MyClass getParent() { ... }

  public MyClass[] getChildren() { ... }

  ....

}

and a subclass

7条回答
  •  爱一瞬间的悲伤
    2021-02-14 18:20

    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

提交回复
热议问题