【java基础】java的this关键字用法,
分享于 点击 16555 次 点评:187
【java基础】java的this关键字用法,
知识点一:this究竟是啥
this代表对当前对象的引用
public class Animal {
public Animal f(){
return this;//当需要返回当前对象的引用时,常常在return语句里这样写。
}
public static void main(String[] args) {
Animal a=new Animal();
Animal b=new Animal();
a.f();//返回a的引用
b.f();//返回b的引用
}
}
知识点二:构造器中调用构造器
源码如下:
public class People {
int age=0;
String name="zhangsan";
People(int age){
this.age=age;//参数名和数据成员age同名,会产生歧义,使用this.age就代表数据成员。
System.out.print("people w/ age"+age);
}
People(int a,String b){
this(a);
name=b;
System.out.print("people age="+age+"name="+name);
}
public void printInfo(){
//this(11);//除了构造器外,编译器禁止在其他任何方法中调用构造器
System.out.print("people age="+age+"name="+name);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
People a=new People(1,"lisi");
a.printInfo();
}
}
知识点3:JAVA的类名.this
this指的是当前正在访问这段代码的对象,当在内部类中使用this指的就是内部类的对象,
为了访问外层类对象,就可以使用外层类名.this来访问,一般也只在这种情况下使用这种
public class Activity01 extends Activity{
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
/* 设置显示main.xml布局 */
setContentView(R.layout.main);
/* findViewById(R.id.button1)取得布局main.xml中的button1 */
Button button = (Button) findViewById(R.id.button1);
/* 监听button的事件信息 */
button.setOnClickListener(new Button.OnClickListener(){
public void onClick(View v){
/* 新建一个Intent对象 */
Intent intent = new Intent();
/* 指定intent要启动的类 */
intent.setClass(Activity01.this, Activity02.class);
/* 启动一个新的Activity */
startActivity(intent);
/* 关闭当前的Activity */
Activity01.this.finish();
}
});
}
}
相关文章
- 暂无相关文章
用户点评