我有一个超类,它是可比的,但是一个孙子类不是。

huangapple go评论74阅读模式
英文:

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&lt;T extends SomeInterface&lt;T&gt;&gt; extends Comparable&lt;T&gt; {...}

Then,

public abstract class SomeClass&lt;T extends SomeClass&lt;T&gt;&gt; extends SomeInterface&lt;T&gt;{...}

And finally,

public class SomeChild extends SomeClass&lt;SomeChild&gt;{...}

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&lt;T&gt;

应改为:

implements SomeInterface&lt;T&gt;

一旦你进行了这个更改,以下代码:

SomeChild s = new SomeChild();
if (s instanceof Comparable)
    System.out.println(&quot;Yup!&quot;);

将会打印出 "Yup!",因为 SomeChild 必须是 Comparable,因为它的祖先是 Comparable,正如你所期望的那样。你的 s 可能是 null 吗?如果是的话,那么 "Yup!" 将不会打印,因为 null 不是任何实例的实例,所以这段代码:

SomeChild s = null;
if (s instanceof Comparable)
    System.out.println(&quot;Yup!&quot;);

将不会打印任何内容。

英文:

The code you show will not compile. The snippet:

extends SomeInterface&lt;T&gt;

should be:

implements SomeInterface&lt;T&gt;

Once you make that change, this code:

SomeChild s = new SomeChild();
if (s instanceof Comparable)
    System.out.println(&quot;Yup!&quot;);

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(&quot;Yup!&quot;);

will not print anything.

huangapple
  • 本文由 发表于 2020年9月8日 09:30:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/63786019.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定