This question already has answers here:
Method chaining + inheritance don’t play well together?

(5个答案)


6年前关闭。





我想用Java编写一个类,该类是一个父类,以从子类中提取内容。

我希望能够使用此代码,但是我不确定Java是否无法使用此代码。

Frodo frodo = new Frodo();
child.addGold(10).goToMordor();


但是这段代码不安全吗?

public class Bilbo
{
    private int gold;

    public Parent()
    {
        // Does something awesome
    }

    public Bilbo addGold(int amount)
    {
        this.gold += gold;
        return this;
    }

    public int getGold()
    {
        return this.gold;
    }
}

// Child class:
public class Frodo extends Bilbo
{
    // Does cool stuff
    public void goToMordor()
    {
        System.out.println("Traveling to Mordor...");
    }
}

最佳答案

您的代码可以用Java编写,而且很安全。不过,对于您来说,在实现中似乎有些奇怪。考虑:

public class Parent{
    private String name;

    public Parent setName(String name){
        this.name = name;
        return this;
    }

    public String getName(){ return this.name;}

    public void print(){
        System.out.println("Say my name!");
    }
}

public class Child extends Parent{
    public void doChildStuff(){
        //child stuff.
    }

    @Override
    public void print(){
        System.out.println(this.getName());
    }
}

Child child = new Child();
//this works as Parent defines print, and setName returns a Parent object.
child.setName("Bill gates").print();

//Compile error, as setName returns Parent, and Parent does not define 'doChildStuff.`
child.setName("Bill Gates").doChildStuff();


您的方法很好,只是要知道链接调用不适用于添加新方法的任何Parent子类。

09-25 18:29
查看更多