如何在JAVA中更改对象的内容?

时间:2015-01-07 20:22:57

标签: java class object

我正在上课,了解JAVA ......

我被告知要添加一个方法(void swapNames(Greeter other))来交换这个greeter和另一个的名字。然后在Greeter类中创建两个对象,并使用swapNames方法交换它们的名称。

我开始......

public class Greeter {

    public Greeter(String aName){
        name = aName;
    }

    public String sayHello(){
        return "Hello, " + name + "!";
    }
    private String name;

    public void swapNames(Greeter other){

    }
}

但我卡住了。如何完成“swapNames()”以更改两个对象的名称?

2 个答案:

答案 0 :(得分:2)

this.name = other.name;

我认为这应该有用。

更新

我忘了你想换掉他们的名字,所以:

String aux = this.name;
this.name = other.getName();
other.setName(aux);

您需要一个setName和getName方法,因为“name”是私有的。

答案 1 :(得分:0)

public void swapNames(Greeter other){
    String temp = name; // holds temp for this name
    name = other.name; // begin swapping
    other.name = temp;
}