Java中的this指针

public class test10 {

    public static void main(String[] args) {
        // 创建一个对象指针。
        ThisPointer tp;
        // tp 保存new出来对象的地址。
        tp = new ThisPointer();
        // 调用行为。
        tp .showAttr();

        // 查看一下tp 的地址。
         System.out.println("tp.Address::"+tp.hashCode());


        
    }
}
// 什么是this 指针。
// Java 虚拟机会给每一个对象分配一个this指针,这个this指针指向当前对象
class ThisPointer{
// 比如这个对象(This Pointer)


    // 定义属性
    int num;
    String str;
    double d;

    ThisPointer()
    {
        // 构造器初始化。
        this.num =10;
        this.str = "Constructor";
        this.d = 3.1415926;

    }

    // 定义行为
    void showAttr()
    {
        // this中的str
        System.out.println(this.str);
        // this 指针中的num
        System.out.println(this.num);
        // this中的d
        System.out.println(this.d);

        // 查看一下this指针的地址。
        System.out.print("this.Address::");
        System.out.println(this.hashCode());
    }
}

// this指针指向当前对象。this指针变量保存当前对象的地址。



// 输出的结果:
// Constructor
// 10
// 3.1415926
// ThisPointer@1edf1c96
// ThisPointer@1edf1c96

// 我们发现tp 和this 指针的地址都是同一个地址,所以this指向自己本身。



// this指针的一些注意事项。
// 1.this指针可以用来访问本类的 属性,行为,构造器
// 2.this 可以用来区分属性和局部变量。
// 访问属性方法 (this.Attr)
// 访问行为(this.behavior)
// 访问构造器(this(aguments))
// this指针只能在本类中使用。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值