相关疑难解决方法(0)

方法链接+继承不能很好地结合在一起?

这个问题已在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 …
Run Code Online (Sandbox Code Playgroud)

java inheritance method-chaining

38
推荐指数
4
解决办法
6626
查看次数

标签 统计

inheritance ×1

java ×1

method-chaining ×1