<分区>
我觉得问题标题有点困惑,但我找不到更准确的说法。
我只需要一个简单的代码示例来告诉您我想要什么。
我有:
// code 1
interface A { A bla(); }
class B implements A { @Override public B bla() { return this; } }
class C implements A { @Override public C bla() { return this; } }
但实际上,这段代码也可以通过编译(区别:查看返回类型声明):
// code 2
interface A { A bla(); }
class B implements A { @Override public A bla() { return this; } }
class C implements A { @Override public A bla() { return this; } }
我希望代码 2 是类型错误。
比如说,我想强制每个 A
的子类的 bla
方法返回它们自己,而不是 A
。
我认为可以有一个假代码来表示我想要的:
interface A { this.Type bla(); }
就像 Haskell 的类型类:
class Monad (m :: * -> *) where
-- here m is restricted to the subclass
(>>=) :: m a -> (a -> m b) -> m b
这可能吗?