gpt4 book ai didi

java - 在其类之外更改 java 对象

转载 作者:行者123 更新时间:2023-11-29 07:13:51 26 4
gpt4 key购买 nike

这是我的问题,我怎样才能在它的类之外更改一个对象,以便它维护在外部类中所做的更改?

代码示例如下:

主类:

    public class Main {

public static void main(String[] args)
{
Variable var = new Variable(1,2,3);
Change.changeVar(var);
System.out.println("" + var.geta() + "" + var.getb() + "" + var.getc());
}
}

变量类:

public class Variable {

private int a;
private int b;
private int c;

public Variable(int a, int b, int c)
{
this.a = a;
this.b = b;
this.c = c;
}

public int geta()
{
return this.a;
}

public int getb()
{
return this.b;
}

public int getc()
{
return this.c;
}

改变等级:

public class Change {

public static void changeVar(Variable var)
{
Variable var2 = new Variable(4,5,6);
var = var2;
}

最佳答案

在你的例子中,没有。当 changeVar() 退出时,参数 var 被丢弃,并且 main() 方法中的 var 保留其原始值。继续阅读 pass by reference .

关于java - 在其类之外更改 java 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11472452/

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