zoukankan      html  css  js  c++  java
  • java引用传递

    1)应用传递就是指将对内存空间的使用权交给多个栈内存空间。

    2)对象的引用传递

     1 class Demo{
     2     int temp = 30;
     3 }
     4 
     5 public class TestJava0583 {
     6 
     7     public static void main(String[] args) {
     8         Demo d1 = new Demo();
     9         d1.temp = 50;
    10         System.out.println("调用之前" + d1.temp);
    11         fun(d1);
    12         System.out.println("调用之后" + d1.temp);
    13         
    14     }
    15     public static void fun(Demo d2){
    16         d2.temp = 1000;
    17     }
    18 
    19 }

    输出结果为:

    调用之前50
    调用之后1000

    分析:调用fun()方法时,d2指向了主函数中new出的对象空间,且用d2修改了此空间的内容,执行fun()方法完毕后,该指向消失。

    3)String类型变量的引用传递

     1 public class RefDemo02 {
     2 
     3     public static void main(String[] args) {
     4         String str1 = "hello";
     5         System.out.println("fun方法调用之前" + str1);
     6         fun(str1);
     7         System.out.println("fun方法调用之后"+ str1);
     8     }
     9     public static void fun(String str2){
    10         str2 = "zhangsan";
    11     }
    12 
    13 }

    输出结果为:

    fun方法调用之前hello
    fun方法调用之后hello

    分析:字符串的内容一旦声明是不可改变的,改变的只是其内存地址的指向。调用fun()方法使str2指向str1所指空间,但是执行str2 = “zhangsan”时,str2的指向不再是str1所指的空间,而是指向另一个空间,将“zhangsan”内容放入其中。

    整个过程中,str2不会影响str1所指空间中的内容。

    4)String作为类的一个属性存在时:

     1 class M{
     2     String temp = "hello";
     3 }
     4 
     5 public class RefDemo03 {
     6 
     7     public static void main(String[] args) {
     8         M d1 = new M();
     9         d1.temp = "world";
    10         System.out.println("fun方法之前" + d1.temp);
    11         fun(d1);
    12         System.out.println("fun方法之后" + d1.temp);
    13     }
    14     public static void fun(M d2){
    15         d2.temp = "zhangsan";
    16     }
    17 
    18 }

    输出结果为:

    fun方法之前world
    fun方法之后zhangsan

    分析:本程序的分析方法和2)中的分析方法一样,因为String时作为类的属性存在的,而在操作时更改的只时类中的属性内容。

  • 相关阅读:
    DevExpress 最最最基础踩坑(如何设置控件属性)
    Oracle如何创建数据库(使用图形化界面,顺便提一下UTF-8和ZB16GB字符集的问题)
    ElementUI el-dialog中嵌套子页面
    Oracle详细教程(触发器,事务,存储过程,锁,游标)
    和人事交谈下来的几点感悟
    Oracle Groupby分组缺少表达式解决方法
    leetcode973. 最接近原点的 K 个点(谈谈C#中的Icomparer,ComParer,IComparable)
    APP的闪退和无响应
    APP测试的主要内容
    python数据结构
  • 原文地址:https://www.cnblogs.com/XuGuobao/p/7233137.html
Copyright © 2011-2022 走看看