this的用法(class.this)

引子:今天看了一些android发现一个东西

java1

public class SimpleService extends Service
{
	public class SimpleBinder extends Binder
	{
		SimpleService getsService()
		{
			return SimpleService.this;
		}
	}
}

java2

activity.this.oncreat();

就以上两种情况分析了一下

public class Myself {

	private int a = 9;

	public Myself() {

	}
  /*  这段代码是就是对 类名.this的理解
               return 类名 是不可用的;
               return 类的实例化是可用的;
               return 类名.this就是return它的实例化。实例化的就是调用者
                下面的 amyself=myself 这里的等于和赋值是相同的,是完全相同
                就是改了个名字
    */
	public Myself myPlay() {

		return Myself.this;
	}
    /*这段是对class.this.ontcreat的理解也就是匿名内部类,中的属性和外部类中属性首先调用谁的问题
    1.如果内部类外部类中只出现一次直接调用即可  就是a
    2.如果重复this.a=a都是调用内部类的
    3.外部类名.a不可以使用,使用方法是外部类名.this.a  因为类名.a和静态方法的使用重复
    */
	public void myPlay2() {
		// Myself.this.myPlay();

		new OutSelf() {
			public void play() {
				System.out.println(a);
				System.out.println(this.a);
				System.out.println(Myself.this.a);
				// System.out.println(Myself.a);这一行会报错,因为a不是static的,上一行就是想实现这一行的效果

			};
		}.play();
	}

	public void setA(int a) {
		this.a = a;
	}

	public int getA() {
		return a;
	}

	public static void main(String[] args) {
		/*
		 * Myself myself=new Myself(); Son son= myself.new Son();
		 * SYSTEM.OUT.PRINTLN();
		 */
		Myself myself = new Myself();
		myself.myPlay2();
		Myself aMyself = myself.myPlay();
		aMyself.myPlay();
		
		myself.setA(0);
		System.out.println(aMyself.getA());
	}
}


其中myplay是对  类名.this

       myplay2是对  类名.this.属性分析

其中都是  类名.this.属性 的时候, 是对内部类和外部类的分析



这里做了一下 ,总结个人理解 ,this可以看做,直属类的实例化,也就是当前代码所属的类的实例化


你在外部实例化之后

不就是 So so=new  So();

so.play();

在类内的一个方法中调用就是:

this.play();

而类名.this.方法;

也是 .this等于实例化。

慢慢理解 this是指向自己的指针


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值