面向对象:引用的传递

1.引用传递

1.1 范例

 class Ref1{
    int temp = 10;
}
public class RefDemo01 {
    public static void main(String  args[]){
        Ref1 r1 = new Ref1();
        r1.temp = 20;
        System.out.println(r1.temp);
        tell(r1);
        System.out.println(r1.temp);
    }
    public static void tell(Ref1 r2){
        r2.temp = 30;
    }
}

02

1.2 范例

public class RefDemo02 {
    public static void main(String[] args){
        String str1 = "hello";
        System.out.println(str1);
        tell(str1);
        System.out.println(str1);
    }
    public static void tell(String str2){
        str2 = "world";
    }
}

**因为String类型的数据是不能更改的,所以str2的指向在tell(str1);的作用下指向了hello
**

03

1.3 范例

class Ref2{
    String temp = "hello";
}
public class RefDemo03 {
    public static void main(String[] args){
        Ref2 r1 = new Ref2();
        r1.temp = "world";
        System.out.println(r1.temp);
        tell(r1);
        System.out.println(r1.temp);
    }
    public static void tell(Ref2 r2){
        r2.temp = "xueyuan";
    }
}

**r1首先是hello,接下来r1被改为world,其实是被开辟了一个新空间,他的指向也被断开,由原先指向hello变为指向world。创建了r2同样也执行world这个值,这样r2也开辟了一个新的空间,然后r2断开连接指向了xueyuan。
**

1.3于1.2的区别在于public static void tell(String str2)public static void tell(Ref2 r2) 第一个是普通的赋值,第二个是实例化,开辟了新的内存空间。所以第二个的String的值会被改变

04

2.this关键字

3.static关键字

暂无评论

发送评论 编辑评论


				
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇
下一篇