this和super && getApplicationContext/getBaseContext/this等的用法

      当一个对象创建后,Java虚拟机(JVM)就会给这个对象分配一个引用自身的指针,这个指针的名字就是this。并且this只和特定的对象关联,而不和类关联,同一个类的不同对象有不同的this。用法:

(1)如果函数的形参与类中的成员变量同名,这时需用this来指明成员变量名

class Point 
{ 
      private int x,y; 
      public Point(int x,int y) 
     { 
           this.x=x; //this它代表当前对象名 
           this.y=y; 
     } 
} 

(2)如果函数的局部变量与成员变量相同时,成员变量会被隐藏。此时如果要用到成员变量的话,就需this。

class Point 
{ 
      private int x = 3; 
      public Point() 
     { 
           int x;
           x = 5;
           system.out.println(x);          //输出5
           system.out.println(this.x);   //输出3
     } 
} 

       来看看super的各种用法

(3)使用特殊变量super提供对父类的访问 

class FatherClass{
    public int value;
    public void f(){
        value = 100;
        System.out.println("FatherClass.value:"+value);
    }
}
class ChildClass extends FatherClass{
    private int value;
    public void f(){
        super.f();
        value=200;
        System.out.println("ChildClass.value:"+value);
        System.out.println(value);
        System.out.println(super.value);
        //super.f();
    }
}

public class main { 	
	public static void main(String[] args) throws  ClassNotFoundException, NoSuchFieldException, Exception{
        ChildClass cc = new ChildClass();
        cc.f();
	}
}
运行结果
FatherClass.value:100
ChildClass.value:200
200
100

(4)对“this通常指代当前对象,super通常指代父类”这句话牢记在心,那么本篇便达到了目的。另一个用到的场合是,super和this后加括号参数,而不是.成员变量或者.成员函数,则是用来调用父类或者子类中具有相同形式的构造函数。Android中,重写方法中调用super方法的位置问题

@ Override
 protected void onCreate(Bundle savedInstanceState) {

  super.onCreate(savedInstanceState);  // 放在第一句

  setContentView(R.layout.content);
  initView();
  .....
}
====================================================================================================================

        getApplicationContext():返回应用的上下文,生命周期是整个应用,应用摧毁它才摧毁。

        getApplication():虽然它返回的是Application对象,但Application类继承自Context,所以它可以用来提供Application Context

Activity.this:返回当前activity的上下文,属于activity ,activity 摧毁他就摧毁

this:表示当前对象;当它表示MainActivity时,也可以用来提供Activity Context

        getContext():这个是View类中提供的方法,在继承了View的类中才可以调用,由于View是跟activity绑定的,返回的是当前View运行在哪个Activity Context中。

        getBaseContext():如下面的例子:

Spinner spinner = (Spinner) findViewById(R.id.spinner);
spinner.setAdapter(adapter);            
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
    @Override
    public void onItemSelected(AdapterView<?>arg0, View arg1, int arg2, long arg3){
       Toast.makeText(getBaseContext(),"SELECTED", Toast.LENGTH_SHORT).show(); //this line
    }
当我把getBaseContext()变成this就会有错误,为什么呢?this是指当前的activity,而上面的场合是指Spinner实例,故要用getBaseContext


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值