java 复习 面向对象2

引用传递及应用
1.三种引用
 基本数据的传递(值的传递)
 eg:
 class Demo()
 {
    int temp = 80;  //堆内存中
 }
 public class Demo01
 {
    public static void main(String args[])
    {
       Demo d1 = new Demo();   //d1在栈内存中 指向堆内存的temp = 80;
       fun(d1);   //调用fun函数 修改temp的值 方法执行完毕以后 d2断开指向
    }
    public static void fun(Demo d2) //d2在栈内存中 指向堆内存中temp = 80;
    {
       d2.temp = 50;               //d2修改了 temp的值
                                   d1和d2都指向 堆内存中的 temp = 50;
    }
 }
 字符串的传递:
 内存地址的传递
 public class Demo1
 {
    public static void main(String args[])
    {
       String str1 = "hello";  //栈内存中str1 指向堆内存中 "hello"
       fun(str1);      //str2与str1都指向hello, str2 = "cyq";
                         方法执行完后str2断开指向hello;
    }
    public static void fun(String str2)//栈内存中str2 指向堆内存中hello
    {
       str2 = "cyq";    //str2在栈内存中指向堆内存中的cyq
    }
 }
 字符串作为属性的传递
 class Demo
 {
   String temp = "hello";  //temp在栈内存中 指向堆内存中的hello
 }
 public class Demo1
 {
    public static void main(String args[])
    {
       Demo d1 = new Demo();  //d1在栈内存中指向 hello;
       d1.temp = "world";     //d1在栈内存中指向 堆内存中的world
       fun(d1);              //修改temp的值,d1指向cyq
    }
    public static void fun(Demo d2) //d2在栈内存中指向堆内存中的world
    {
       d2.temp = "cyq";            //fun(d1)传进来后修改temp的属性值
    }
 }
 String作为类对象传递是地址,作为类对象的属性时传递的是字符串值
 总体来说,在java中,不管是引用类型还是基本数据类型,传递的都是值.

 2.接收本类的引用
   自己接收自己本类的引用对象
   只要符合引用传递的语法,则可以向任意的地方传递
  eg:
  class Demo
  {
    private int age;

    public void setAge(int age)
    {
      this.age = age;
    }
    public int getAge()
    {
       return age;
    }

    public void fun(Demo d2)//接收本类对象的引用
    {
       d2.age = 45;       //通过对象调用本类的私有属性
    }

    public static void main(String args[])
    {
        Demo d1 = new Demo();//实例化对象
 d1.setAge(45);     //通过set方法设置属性
 
 d1.fun(d1);     //把d1传进方法中设置age属性
    }
  }

  3.传递的应用
    一对一的关系
    一个人有一本书,一本书属于一个人

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值