java 返回this,关于Java子类,其继承方法返回“ this”。

Have a class Car with a public method

public Car myself() {

return this;

}

Have a subclass Ferrari, and a variable foo that contains a Ferrari object.

Finally,

Ferrari bar = foo.myself();

This will warn you, because the method myself() returns a Car object, rather than the expected Ferrari.

Note: I know that the example is stupid because you'd just do bar = foo. It's just an example.

Solutions:

Override the myself() method in Ferrari.

Cast the Car object to a Ferrari object when assigning bar.

Both solutions work and I am okay with that. However, the first one is undesirable when you have several subclasses of Car. I feel that overriding a method over and over defeats the point of inheriting it. Next, regarding the second solution, casting is not pretty. It feels silly - if my variable is of type Ferrari, shouldn't Java be able to implicitly cast it without warning me? After all, Java must know that the returned object can be casted to Ferrari, no?

Is there another workaround? Just out of curiosity - I can live with casting stuff, telling Java what things are supposed to be...

解决方案

This solution uses generics in a way that is used more often in the Java libraries.

It works and you don't have to cast the result every time nor override the myself method in every subclass.

I believe that it is the only solution that doesn't require overriding or casting. It does require each subclass to use its own type as a type parameter to the superclass Car: class Ferrari extends Car

class Car> {

public X myself() {

return (X) this;

}

}

class Ferrari extends Car {

}

And then use it as you intended:

Ferrari testarossa = new Ferrari().myself();

This concept is used in the Java standard libraries a few times as well in one way or another:

java.lang.Enum

public abstract class Enum>

java.util.Comparable

public interface Comparable

(You're supposed to pass your own class type when you implement a comparable: class ShoeSize implements Comparable)

Method chaining

There's a good use for this too - there is a pattern, favored by some, that allows method chaining. This is what StringBuilder does: new StringBuilder().append("a").append("b").toString(). However a class that supports method chaining is often hard to subclass. Using the approach I outlined above makes it possible to subclass in this situation.

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值