this与static的爱恨情仇

1. this与实例化对象的关系

this是Java虚拟机在创建对象时自动创建的指向该对象的指针
this用于方法中,而this指代的是该方法所属类的当前对象(当前实例化对象

输出对象地址与this地址


//输出对象地址与this地址
> public class ref_03 {
    int number = 18;
    public static void main(String[] args) {       
        ref_03 r3 = new ref_03();
        ref_03 r2 = new ref_03();
       r3.say(r2);//这里r3表示say()所属类的当前对象,即this指针指向的地址
    }
     
    public void say(ref_03 r5){
        System.out.println(this);
        System.out.println(r5);
        
    }
}


2. 通过实例化对象实现在static方法中调用non-static方法or属性

在main方法中实例化了两种对象,通过这两个实例化的对象实现了在static main函数中调用非静态变量,方法同理

class ref_int{
    int i = 20;

}
public class ref_03 {
    int number = 18;
    public static void main(String[] args) {
        ref_int r1 = new ref_int();
        ref_03 r3 = new ref_03();
        ref_03 r2 = new ref_03();
        r1.i = 30;
        System.out.println(r1.i);
        System.out.println(r2.number);
        System.out.println(r3.say(r1,r2));//这里r3表示say()所属类的当前对象,即this指针指向的地址
    }
     public  int tell(ref_int r2){
        r2.i = 40;
        this.number = 200;
        return r2.i;

    }

3. 为什么在main函数中实例化对象后仍然无法用this引用non-static属性,方法

main函数中的this属于main函数,而main属于类本身,而不是已经实例化的对象,所以实例化的对象与this无关,尽管main函数被包含在该对象中.

类中方法其实分为两种;一种是实例所属的方法,一种是类本身拥有的方法,从调用方法的方式上可以看出这点.

People.name();//静态方法从属于类本身
Juddy.name();//非静态方法从属于对象


撒由那拉,下次见.

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值