简体   繁体   中英

Is it possible to set the return type of an abstract method to be the same as the class?

我想将抽象方法的返回类型设置为与类相同,而不是抽象类的类型,但与继承类的类型相同。

You can use the self-type pattern:

abstract class A<T extends A<T>> {
    abstract T foo();
}

class B extends A<B> {
    B foo() {
        return this;
    }
}

All three of these do exactly the same thing.

public class TestAbstract {
   public static void main(String[] args) {
      B b1 = new B();
      A a1 = b1.getMyClass();
      System.out.println(a1.getClass().getName());
      A a2 = b1.getItThisWay();
      System.out.println(a2.getClass().getName());
      A a3 = b1;
      System.out.println(a3.getClass().getName());
   }
}

abstract class A {
   abstract public A getMyClass();
}

class B extends A {
   public A getMyClass() {
      return this;
   }

   public A getItThisWay() {
      return this;
   }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM