Avoid casting in inherited java-classes

前端 未结 7 1954
执念已碎
执念已碎 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:34

    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.

提交回复
热议问题