引用传递
引用传递时java的精神所在,引用传递的核心:同一个堆内存可以被多个栈内存所指向。,不同栈内存可以对同一个堆内存进行修改。
引用传递案例1
class Person{
private int age;
public Person(int age){
this.age = age;
}
public void setAge(int age){
this.age = age;
}
public int getAge(){
return this.age;
}
}
public class TestQuote{
public static void main(String[] arg){
Person person = new Person(25);
System.out.println(person.getAge());//结果25
fun(person);
System.out.println(person.getAge());//结果27
}
public static void fun(Person temp){
temp.setAge(27);
}
}
String引用传递案例1
如下代码:对象未被改变,输出还是bobo。这个原因时字符串时不表的,你temp=“boboyoucan”后,temp的指向就变了,变成了指向字符串“boboyoucan”的堆内存
public class TestQuote{
public static void main(String[] arg){
String a = "bobo";
fun(a);
System.out.println(a);//bobo
}
public static void fun(String temp){
temp= "boboyoucan";
}
}
String引用传递案例2
class Person{
private String name;
public Person(String name){
this.name = name;
}
public void setName(String name){
this.name = name;
}
public String getName(){
return this.name;
}
}
public class TestQuote{
public static void main(String[] arg){
Person person = new Person("bobo");
fun(person);
System.out.println(person.getName());//结果boboyoucan
}
public static void fun(Person temp){
temp.setName("boboyoucan");
}
}