Avoid casting in inherited java-classes

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

    Yes, assuming that you know that the parent and children of a MySubClass will always be of type MySubClass.

    In that case you could just narrow the return types in MySubClass and do the casting there:

    MySubClass extends MyClass() {
        @Overrides
        public MySubClass getParent() { return (MySubclass) super.getParent(); }
    
        @Overrides
        public MySubClass[] getChildren() { return (MySubclass[]) super.getChildren(); }
    
        public String getId() { }
    
        ...
    }
    

提交回复
热议问题