Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/395.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在JAVA中更改对象的内容?_Java_Class_Object - Fatal编程技术网

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

如何在JAVA中更改对象的内容?,java,class,object,Java,Class,Object,我正在学习一门关于JAVA的课程 我被告知要添加一个方法void swapNamesGreeter other,该方法交换这个问候者和另一个问候者的名字。然后在Greeter类中创建两个对象,并使用swapNames方法交换它们的名称 我从 public class Greeter { public Greeter(String aName){ name = aName; } public String sayHello(){ retu

我正在学习一门关于JAVA的课程

我被告知要添加一个方法void swapNamesGreeter other,该方法交换这个问候者和另一个问候者的名字。然后在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以更改两个对象的名称

this.name = other.name;
我认为这应该行得通

更新:

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

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

因为名称是私有的,所以您需要一个setName和getName方法。

用外行的话说,您尝试过什么?如何交换两个存储桶的内容?最简单的方法是使用另一个铲斗。将存储桶A的内容放入附加存储桶,然后从B放入A,然后从附加存储桶放入B。这将如何交换它们的名称?好吧,现在它不能用java编译了。您仍然无法执行其他操作。name;对不起,我注意到了,修正了:@austinwernli你说你仍然不能做其他的事是什么意思。name;?Greeter类可以访问其所有字段,无论它们是在本实例中还是在其他实例中。您是对的!我弄错了,对不起
public void swapNames(Greeter other){
    String temp = name; // holds temp for this name
    name = other.name; // begin swapping
    other.name = temp;
}