這個問題是在C ++上下文中提出的,但是我對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(有效地)改變對象類型呢?
3 回答
慕妹3242003
TA貢獻1824條經驗 獲得超6個贊
不,不是。您可以使用協變返回類型來解決它(感謝McDowell提供正確的名稱):
@Override
public Cat setName(String name) {
super.setName(name);
return this;
}
(如果您很擔心,協變返回類型僅在Java 5及更高版本中可用。)
添加回答
舉報
0/150
提交
取消
