Avoid casting in inherited java-classes

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

    Depending on what you are actually trying to do, either make your base class abstract and add getId():

    abstract class MyClass() {
        public MyClass getParent() { ... }
        public MyClass[] getChildren() { ... }
        public String getId();
        ....
    }
    
    MySubClass extends MyClass() {
        @Overrides
        public String getId() { }
        ...
    }
    

    Alternatively, depending on your requirements, implement getId() in your base class:

    class MyClass() {
        public MyClass getParent() { ... }
        public MyClass[] getChildren() { ... }
        public String getId() { }
        ....
    }
    
    MySubClass extends MyClass() {
        ...
    }
    

提交回复
热议问题