英文:
I have a superclass that is Comparable, but a grandchild is not
问题
我正在实现一个带有以下类定义的层次结构:
public interface SomeInterface<T extends SomeInterface<T>> extends Comparable<T> {...}
然后,
public abstract class SomeClass<T extends SomeClass<T>> extends SomeInterface<T> {...}
最后,
public class SomeChild extends SomeClass<SomeChild> {...}
对于一个 SomeChild s,s instanceof Comparable
返回 false。
我希望能够在 SomeChild 的 ArrayList 上调用 Collections.sort()
,但运行时会抛出编译时错误,指示 ClassCastException
,因为无法将 SomeChild 强制转换为 Comparable,我对此感到困惑。如果一个超类扩展了 Comparable,为什么它的子类不能呢?
英文:
I am implementing an hierarchy with the class definitions as follows:
public interface SomeInterface<T extends SomeInterface<T>> extends Comparable<T> {...}
Then,
public abstract class SomeClass<T extends SomeClass<T>> extends SomeInterface<T>{...}
And finally,
public class SomeChild extends SomeClass<SomeChild>{...}
For a SomeChild s, s instanceof Comparable
returns false.
I want to be able to call Collections.sort()
on an ArrayList of SomeChilds, but running it throws a compile-time error of a ClassCastException
because SomeChild cannot be cast to a Comparable and I'm scratching my head as to why. If a superclass extends Comparable, why can't its child?
答案1
得分: 3
代码示例将无法编译。片段:
extends SomeInterface<T>
应改为:
implements SomeInterface<T>
一旦你进行了这个更改,以下代码:
SomeChild s = new SomeChild();
if (s instanceof Comparable)
System.out.println("Yup!");
将会打印出 "Yup!",因为 SomeChild
必须是 Comparable
,因为它的祖先是 Comparable
,正如你所期望的那样。你的 s
可能是 null
吗?如果是的话,那么 "Yup!" 将不会打印,因为 null
不是任何实例的实例,所以这段代码:
SomeChild s = null;
if (s instanceof Comparable)
System.out.println("Yup!");
将不会打印任何内容。
英文:
The code you show will not compile. The snippet:
extends SomeInterface<T>
should be:
implements SomeInterface<T>
Once you make that change, this code:
SomeChild s = new SomeChild();
if (s instanceof Comparable)
System.out.println("Yup!");
WILL print "Yup!" because SomeChild must be a Comparable since its ancestors are, as you expect. Is your s
possibly null
? If it were, then "Yup!" would not print because null
is not an instance of anything, and so this code:
SomeChild s = null;
if (s instanceof Comparable)
System.out.println("Yup!");
will not print anything.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论