這個(gè)問題是在C ++上下文中提出的,但是我對(duì)Java很好奇。關(guān)于虛擬方法的擔(dān)憂并不適用(我認(rèn)為),但是如果您遇到這種情況: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}在這種類層次結(jié)構(gòu)中,是否有任何方法可以this(有效地)改變對(duì)象類型呢?
方法鏈接+繼承不能一起發(fā)揮作用嗎?
函數(shù)式編程
2019-10-18 09:58:15