java代表类自身,我们可以代表“自类”吗?在Java(或Kotlin)中?

I think the question title is a little bit confusing, but I can't find a more precise way to say this.

I just need a simple code example to tell you what I want.

I have:

// 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; } }

But actually, this code will compile too (diff: look at the return type declaration):

// 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; } }

I want code 2 to be a type error.

Say, I want to force every A's subclass' bla method to return their self, instead of an A.

I think there can be a fake code to represent what I want:

interface A { this.Type bla(); }

Just like Haskell's typeclasses:

class Monad (m :: * -> *) where

-- here m is restricted to the subclass

(>>=) :: m a -> (a -> m b) -> m b

Is this possible?

解决方案

Not possible, but you can do that

interface A { T bla();}

class B implements A { @Override public B bla() { return this; } }

class C implements A { @Override public C bla() { return this; } }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值