-1 java
public class testtype
{
private int a;
private double b;
testtype(int a,double b)
{
this.a=a;
this.b=b;
}
public void maketoequal(testtype oo)
{
oo.a=this.a;
oo.b=this.b;
}
void trytoequal(int c)
{
c=this.a;
}
public static void main(String[] args)
{
testtype t1,t2;
t1=new testtype(10,15.0);
t2=new testtype(5,100.0);
t1.maketoequal(t2);
System.out.println("after the method is called:"+"\n"+"the value of a for t2 is:"+t2.a
+"\n"+"the value of b for t2 is :"+t2.b);
int c=50;
t1.trytoequal(c);
System.out.println("the value of c after the method be called is:"+c);
}
}
Run Code Online (Sandbox Code Playgroud)
为什么c没有改变?
Java 按值传递参数(因此在方法中创建并在本地使用该值的副本)。
对于原始类型 - 在您的情况下为 c -,该值是 c 的值,因此您使用 c 的值的副本并且您不会更改 c
对于对象,值是引用的值,因此即使您按值传递它(复制它),它仍然引用同一个对象,您可以使用引用的副本更改对象...
| 归档时间: |
|
| 查看次数: |
2757 次 |
| 最近记录: |