Because Java cancels the concept of pointers, developers often ignore the difference between objects and references in programming, such as Example 1
package xupt.edu.java.com;
public class TestRef
{
public Obj aObj = new Obj();
private int aInt = 0;
public Obj getAObj()
{
return aObj;
}
public int getAInt()
{
return aInt;
}
public void changeObj(Obj inObj)
{
inObj.setStr("changed value");
}
public void changeInt(int inInt)
{
inInt = 1;
}
public static void main(String[] args)
{
TestRef oRef = new TestRef();
System.out.println("*********引用类型*********");
System.out.println("调用changeObj()前:" + oRef.getAObj());
oRef.changeObj(oRef.getAObj());
System.out.println("调用changeObj()后:" + oRef.getAObj());
System.out.println("*********基本数据类型*********");
System.out.println("调用changeInt()前:" + oRef.getAInt());
oRef.changeInt(oRef.getAInt());
System.out.println("调用changeInt()后:" + oRef.getAInt());
}
}
class Obj
{
public void setStr(String str)
{
this.str = str;
}
private String str = "default value";
public String toString()
{
return str;
}
}
The above two seemingly similar methods have different results. The main reason is that Java handles basic data types (such as int, char, double, etc.) by using value-by-value transfer (the input parameter is copied) Implementation, other types are executed by reference (passing a reference to an object).