java中this详解

一些刚接触java的新手会有对this有这样那样的困惑,本文将尽我所能解释java中this的用法。

this说白了,指的就是当前对象。看如下代码:

public   class  TestThis  {
    
int i = 1;
    TestThis(
int i){
        System.out.println(”i
=+i);
        System.out.println(”
this.i=+this.i);
    }

    
public class Another{
        
int i=3;
        Another(
int i){
            System.out.println(”i
=+i);
            System.out.println(”
this.i=+this.i);
            System.out.println(”TestThis.
this.i=+TestThis.this.i);
        }

    }

    
public static void main(String[] args){
        TestThis t
=new TestThis(2);
        TestThis.Another a
=t.new Another(4);
    }

}

 

/*Output:
i=2
this.i=1
i=4
this.i=3
TestThis.this.i=1
*///:~

看内部类的构造函数输出分别是:

i=4
this.i=3
TestThis.this.i=1

i表示的是你传进去的参数;this.i指的是当前对象的i,就是内部类的i;TestThis.this.i表示的是TestThis的当前对象的i。为什么要引入this呢?就像内部类,有两个i,一个是局部变量,一个是内部类的变量。怎么区分这两个i呢?所以就引入了this;在创建类的时候new TestThis();的时候,java在底层吧new这个对象的引用传给了自己。我们怎么调用传给自己的这个对象呢,就是用this。而this.xxx指的就是当前对象的xxx。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值