0

让我们以这段代码为例:

import java.awt.*;

class Maze extends Panel{

    String name;

    public static void main(String[] args){
        Maze m = new Maze();
        System.out.println(m.setName("Hello World").getName());
    }

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

    public String getName(){
        return name;
    }

    public void paint(){

    }
}

我正在尝试理解方法链接,并且正如其他问题的答案所说,使用return this. 我试过了,是的,它可以工作,但不能像上面的方法那样使用 mutator 方法setName()。为什么编译器输出:

The return type is incompatible with Component.setName(String)
4

2 回答 2

8

你给的代码应该没问题。

但是,我怀疑问题在于您的真实代码是扩展类Component,并且您正在尝试覆盖 setName.

也许相反,您可以编写一个withName方法,如下所示:

public Maze withName(String name) {
    setName(name); // Inherited method
    return this;
}

...尽管您应该知道它withXyz经常在 API 中用于创建类型的实例(特别是不可变类型),而不是修改现有实例。

于 2012-04-16T10:41:03.443 回答
3

除非 Maze 派生自其他定义setName(String)的类,否则Maze setName(String name)签名应该是完全可以接受的

注意:你应该写this.name = name;

UPDATE: as it turns out, Maze is deriving from a Panel (which is deriving from Component). As Component.setName(String) specifies its return type as void (void setName(String)), you cannot specify any other return type, but void for setName() in your class. The reason is inheritance: if someone has a reference to your Maze object via a Component reference (e.g. Component c = new Maze();), and calls setName(), the runtime knows to call yours, because of the inheritance. However your version is returning a value, with which the runtime has to do something, but the code is not prepared for it (it was compiled with the knowledge of a Component.

于 2012-04-16T10:41:40.937 回答