Java中的OOP:使用方法链接的类继承

Mic*_*ael 15 java oop

我有一个父类,它定义了一个chainer方法的集合(返回"this"的方法).我想定义多个子类,这些子类包含自己的chainer方法,但也"覆盖"父方法,以便返回子类的实例而不是父类.

我不想在每个子类中重复相同的方法,这就是为什么我有一个包含所有子类共享的方法的父类.谢谢.

class Chain {
  public Chain foo(String s){
    ...
    return this;
  }
}

class ChainChild extends Chain {
  //I don't want to add a "foo" method to each child class
  /*
  public ChildChain foo(String s){
    ...
    return this;
  }
  */

  public ChainChild bar(boolean b){
    ...
    return this;
  }
}

ChainChild child = new ChainChild();
child.foo().bar(); //compile error: foo() returns a "Chain" object which does not define the bar() method. 
Run Code Online (Sandbox Code Playgroud)

Old*_*eon 13

返回的父类中的方法this仍将返回对子类的对象的引用.您将只能将其视为父类的对象(除非您将其强制转换),但实际上它将是其原始类型.

你可以考虑使用这样的泛型:

// This seems a bit too contrived for my liking. Perhaps someone else will have a better idea.
public class Parent<T extends Parent<T>> {
    T foo () {
        return (T) this;
    }
}

public class Child extends Parent<Child> {
    public void bar () {
        Child c = foo();
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 我认为@ luiggi的技术可能比较整洁. (2认同)

Lui*_*oza 11

我根据您的需要使用泛型编写了这个示例.

class Parent {
    public <T extends Parent> T foo() {
        return (T)this;
    }
}

class Child extends Parent {

}

class AnotherChild extends Parent {

}

public class Test {
    public static void main(String[] args) {

        Parent p = new Child();
        System.out.println(p);
        Child c = p.foo();
        System.out.println(c);
        //throws ClassCastException here since Child is not AnotherChild
        AnotherChild ac = p.foo();
        System.out.println(ac);
    }
}
Run Code Online (Sandbox Code Playgroud)