java多级继承_java – 方法链接:如何在多级继承的情况下使用getThis()技巧

你的问题的根源是一个类设计问题:你试图从一个具体的类继承,这几乎总是一个错误,并且(你的例子)必然会导致许多问题.要坚持参考线程中给出的例子,你不应该实例化狗,因为在这样的宇宙中,一般不存在狗,只有宠物 – 只有贵宾犬,纽芬兰,西班牙人等.因此,getThis不应该是在中级(抽象)类中实现,仅在(具体)叶类中实现.在所有中级抽象类中,您应该只引用泛型类型参数T,而不是实际的类名.

public class TestClass {

static abstract class Pet > {

private String name;

protected abstract T getThis();

public T setName(String name) {

this.name = name;

return getThis(); }

}

static class Cat extends Pet {

@Override protected Cat getThis() { return this; }

public Cat catchMice() {

System.out.println("I caught a mouse!");

return getThis();

}

}

// Dog is abstract - only concrete dog breeds can be instantiated

static abstract class Dog> extends Pet {

// getThis is not implemented here - only in concrete subclasses

// Return the concrete dog breed, not Dog in general

public T catchFrisbee() {

System.out.println("I caught a frisbee!");

return getThis();

}

}

static class Poodle extends Dog {

@Override protected Poodle getThis() { return this; }

public Poodle sleep() {

System.out.println("I am sleeping!");

return getThis();

}

}

static class NewFoundland extends Dog {

@Override protected NewFoundland getThis() { return this; }

public NewFoundland swim() {

System.out.println("I am swimming!");

return getThis();

}

}

public static void main(String[] args) {

Cat c = new Cat();

c.setName("Morris").catchMice();

Poodle d = new Poodle();

d.setName("Snoopy").catchFrisbee().sleep();

NewFoundland f = new NewFoundland();

f.setName("Snoopy").swim().catchFrisbee();

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值