gpt4 book ai didi

java - 更新 Java 中的现有变量

转载 作者:行者123 更新时间:2023-12-01 19:30:30 26 4
gpt4 key购买 nike

我有以下代码作为示例(我删除了大部分代码以使其更容易)

主类:

class TestStudent_3
{
// To update student name to other name
private void updateObject (Student s, String otherName)
{
s.setName (otherName);
}

public static void main (String [] args)
{
... All variables, methods and scanner inputs etc removed ...

Student s = new Student (name, gender, age, subject1, subject2);
s.displayStudentInfo ();

// If you wish to change one the fields, you need to use mutator methods
TestStudent_3 ts = new TestStudent_3 ();
ts.updateObject (s, "New Name");
s.displayStudentInfo ();
}
}

学生类(class):

class Student
{
private String name;

... All variables, methods and scanner inputs etc removed ...

public void setName (String name)
{
this.name = name;
}
}
<小时/>

我的问题是 main 方法中的这几行是做什么的?为什么它可以更新现有记录

TestStudent_3 ts = new TestStudent_3 ();

这是在做什么?创建一个新对象 ts?

ts.updateObject (s, "New Name");

将 Student 的对象变量(内容)与“New Name”字符串一起传递给 updateObject 方法,为什么会这样?

提前致谢!

最佳答案

分解它。

s.setName(otherName);

将实例 s 中的名称设置为 otherName

ts.updateObject (s, "New Name");

就像某种代理一样。它接受 s 的实例和名称,然后在 updateObject 方法中执行相同的操作。

关于java - 更新 Java 中的现有变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59864220/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com