我正在寻找一些如下所示的代码:
public class Parent<T is_or_extends Parent<T>> {
public T function() {
// do some stuff //
return correct();
}
public T correct() {
return (T) this;
}
}
这样任何子类都可以访问其他父函数,但仍保持独立的类(不会将 function() 的返回值向上转换为 Parent 的实例)。
程序员也可以独立使用 Parent 类(因此可以创建 Parent 的实例,而无需 function() 向下转换返回对象)
执行:
public class Child extends Parent<Child> {}
Usage:
Child child = new Child(); // ok
Parent<Child> polymorph = new Child(); // ok
Parent<Parent> parent = new Parent<Parent>(); // ERROR!
只是为了概述差异,这不是方法链接的问题。相反,当父类采用子类的泛型时,它不能再单独用作类(使用上面的代码),因为new Parent<Parent>()
将无法编译(当替换“is_or_extends
" with "extends
")
My Goal:
我的目标是实现一个父类,当扩展时,function()
将返回子类的对象而不是父类的对象。
我会使用泛型类型来告诉父类哪个子类调用了该函数,但我不能再使用父类本身的对象而不遇到异常。示例如下:
public static class Parent<T extends Parent<T>> {}
public static class Child extends Parent<Child> {}
public static void main(String[] args) {
// This will not compile as Parent cannot extend Parent
Parent<Parent> parent = new Parent<Parent>();
// This will work as Child extends Parent
Child child = new Child();
}
提前致谢。
extends
does意思是“是或延伸”。您的示例无法编译的原因是因为内部Parent
是原始类型,不能有效替代T extends Parent<T>
。 “正确”的类型如下所示:Parent<Parent<Parent<...>>>
无穷无尽。显然这样的类型是不可能声明的。
一种解决方案是像这样实例化它:
Parent<?> parent = new Parent<>();
Parent<?> derived = parent.function();
这是有效的,因为编译器已经知道T
是某个子类Parent<?>
。此技巧的一个缺点是,如果无法推断类型,则该技巧将不起作用,例如在使用匿名类时。
另一种可能的方法 - 取决于父/子关系的性质 - 是创建一个附加类来扩展基类,仅用于其类型解析:
// Parent functionality in here
public static abstract class Base<T extends Base<T>> {}
// This can be empty, or have just constructors if necessary
public static class Simple extends Base<Parent> {}
// Child functionality in here
public static class Extended extends Base<Extended> {}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)