gpt4 book ai didi

java - 我可以更改对象的变量吗

转载 作者:行者123 更新时间:2023-12-02 04:23:14 27 4
gpt4 key购买 nike

我有一个可以保存姓名和标记的学生对象。

public class Student{
Public String name;
Public int mark;
public Student (int argMark, String argName)
{ mark=argMark; name=argName;}
}

当我创建一个学生时:

  Student john = new Student(70, "John");

我需要稍后更改标记,同时保留之前的标记

  Student temp = john; 
temp.mark = 60;

当我打印出来时,它们都有 60 分

 System.out.println(temp.mark);
System.out.println(john.mark);

系统显示两人的答案都是:60

我知道我可以扩展一个类并拥有一个获取方法、设置方法并覆盖它,但这对于我的作业来说是 Not Acceptable 。还有其他方法可以做到这一点吗?

最佳答案

您可以创建复制构造函数,这样您就可以在 temp 中获得具有相同属性值的新引用。目前 JohnTemp 具有相同的引用,其中一个的更改将反射(reflect)在另一个中。

public Student (Student student) { 
this.mark = student.getMark();
this.name = student.getName();
}

一些建议,

关于java - 我可以更改对象的变量吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32514388/

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