java - 更新 Java 中的现有变量

标签 java

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

主类:

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/

相关文章:

java - Websphere中的这些线程池有什么区别?

java - 如何在 Linux JVM 中使用 native Windows DLL

java - 使用 Jmeter 对独立 Java 应用程序进行负载测试

java - 缺少返回语句错误

java - Android 应用程序未在 KitKat 中运行

java - JMockit:模拟接口(interface)时为 "Misplaced argument matcher detected here"

java - 在运行时设置属性文件内的值

java - Jersey 客户端收到错误的响应

java - JasperReports 中的软连字符支持

java - 如何使用 Spring 在 OAuth2 身份验证中生成客户端 key