【发布时间】:2010-11-07 08:36:41
【问题描述】:
This question has been asked in a C++ context 但我对 Java 很好奇。对虚拟方法的担忧不适用(我认为),但如果你有这种情况:
abstract class Pet
{
private String name;
public Pet setName(String name) { this.name = name; return this; }
}
class Cat extends Pet
{
public Cat catchMice() {
System.out.println("I caught a mouse!");
return this;
}
}
class Dog extends Pet
{
public Dog catchFrisbee() {
System.out.println("I caught a frisbee!");
return this;
}
}
class Bird extends Pet
{
public Bird layEgg() {
...
return this;
}
}
{
Cat c = new Cat();
c.setName("Morris").catchMice(); // error! setName returns Pet, not Cat
Dog d = new Dog();
d.setName("Snoopy").catchFrisbee(); // error! setName returns Pet, not Dog
Bird b = new Bird();
b.setName("Tweety").layEgg(); // error! setName returns Pet, not Bird
}
在这种类层次结构中,有没有办法以不(有效)向上转换对象类型的方式返回 this?
【问题讨论】:
-
现在我明白为什么这么多人讨厌 Java。
标签: java inheritance method-chaining