Avoid casting in inherited java-classes

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

    Maybe using generics (http://docs.oracle.com/javase/tutorial/extra/generics/index.html)

    You should have something like this:

    public class MyClass {
    
        public T getParent() { return null; }
    
        public MyClass[] getChildren() {
            return null;
        }
    
        public static void main(String[] args) {
            MyClass o = new MySubClass();
            o.getParent().getId();
        }
    }
    
    class MySubClass extends MyClass {
    
        public String getId() {
            return "";
        }
    }
    

提交回复
热议问题