引用传递

引用传递时java的精神所在,引用传递的核心:同一个堆内存可以被多个栈内存所指向。,不同栈内存可以对同一个堆内存进行修改。

引用传递案例1
  1. class Person{
  2. private int age;
  3. public Person(int age){
  4. this.age = age;
  5. }
  6. public void setAge(int age){
  7. this.age = age;
  8. }
  9. public int getAge(){
  10. return this.age;
  11. }
  12. }
  13. public class TestQuote{
  14. public static void main(String[] arg){
  15. Person person = new Person(25);
  16. System.out.println(person.getAge());//结果25
  17. fun(person);
  18. System.out.println(person.getAge());//结果27
  19. }
  20. public static void fun(Person temp){
  21. temp.setAge(27);
  22. }
  23. }

int引用传递图解

String引用传递案例1

如下代码:对象未被改变,输出还是bobo。这个原因时字符串时不表的,你temp=“boboyoucan”后,temp的指向就变了,变成了指向字符串“boboyoucan”的堆内存

  1. public class TestQuote{
  2. public static void main(String[] arg){
  3. String a = "bobo";
  4. fun(a);
  5. System.out.println(a);//bobo
  6. }
  7. public static void fun(String temp){
  8. temp= "boboyoucan";
  9. }
  10. }

String引用传递案例2
  1. class Person{
  2. private String name;
  3. public Person(String name){
  4. this.name = name;
  5. }
  6. public void setName(String name){
  7. this.name = name;
  8. }
  9. public String getName(){
  10. return this.name;
  11. }
  12. }
  13. public class TestQuote{
  14. public static void main(String[] arg){
  15. Person person = new Person("bobo");
  16. fun(person);
  17. System.out.println(person.getName());//结果boboyoucan
  18. }
  19. public static void fun(Person temp){
  20. temp.setName("boboyoucan");
  21. }
  22. }