对于this关键字,都不陌生,只要在java程序代码中都可见,下面是android中绑定按钮监听一段代码:
点击(此处)折叠或打开
-
button1.setOnClickListener(new OnClickListener() {
-
-
@Override
-
public void onClick(View v) {
-
// TODO 自动生成的方法存根
-
Intent intent = new Intent(MainActivity.this,SecondActivity.class);//传入MainActivity作为上下文
-
startActivity(intent);
-
//MainActivity.this.startActivity(intent);
-
}
- });
下面看一段很常见的代码:
点击(此处)折叠或打开
-
public class this1{
-
-
private int i;
-
-
this1(int i){
-
this.i = i;
-
this.geti();
-
this1.printname();
-
int c = 0;
-
}
-
-
static{
-
-
int i = 9;
-
System.out.println("static块中的i:" + i);
-
}
-
public void geti(){
-
-
System.out.println(this.i);
-
this.printname();
-
}
-
public static void printname(){
-
-
System.out.println("lios");
-
}
-
public static void main(String[] args){
-
-
new this1(1);
-
//geti();静态方法内不可以调用非静态方法,反之可以
-
}
- }
构造函数也是一个特殊的static方法,它没有返回值,我是这样理解的,在new出一个对象时系统自动调用了构造函数,用来初始化实例;在类中如果有static方法块时(如上图),系统加载时,首先初始化static字段以及方法,然后才调用构造器,两者有相似之处。上述个人看法可以说是无稽之谈,当然深入的理解java构造器,还需要理解JVM机制,鉴于本人水平有限,这里不作分析。
下面看一个很有趣的程序:
点击(此处)折叠或打开
-
public class This1 {
-
-
public int i = 0;
-
-
public This1 getthis(){
-
i++;
-
return this;
-
}
-
public void geti(){
-
-
System.out.println(i);
-
}
-
public static void main(String[] args){
-
-
This1 th = new This1();
-
th.getthis().getthis().getthis().getthis().geti();
-
System.out.println(th);
-
System.out.println(th.getthis());
-
System.out.println(th.getthis().getthis());
-
System.out.println(th.getthis().getthis().getthis());
-
System.out.println(th.getthis() == th.getthis().getthis());
System.out.println(th.getthis().getthis()== th.getthis().getthis().getthis().getthis());
-
}
- }
下面的代码也许会有点新奇:
点击(此处)折叠或打开
-
public class Thiss {
-
private int i;
-
Thiss(int i){
-
-
int j = i;
-
System.out.println("j:"+j);
-
}
-
public Thiss(String ss) {
-
this(1);
-
String s = ss;
-
System.out.println("s:"+s);
-
}
-
public Thiss() {
-
this("diy_os");
-
}
-
-
public static void main(String[] args){
-
- new Thiss();
- }
}
this可以将当前对象传给其他方法:
点击(此处)折叠或打开
-
public class Person {
-
public void eat(Apple apple){
-
Apple appled = apple.getPeeled();
-
System.out.println("Yummy");
-
System.out.println(appled);
-
}
-
}
-
-
public class Peeler {
-
static Apple peel(Apple apple){
-
-
return apple;
-
}
-
}
-
-
public class Apple {
-
-
Apple getPeeled(){
-
return Peeler.peel(this);
-
}
-
}
-
-
public class PassingThis {
-
-
public static void main(String[] args){
-
-
Apple A = new Apple();
-
new Person().eat(A);
-
System.out.println(A);
-
System.out.println(A.getPeeled());
-
}
- }
文章用于学习总结,如有不当错误之处,请读者指正!谢谢!
来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/29876893/viewspace-1839283/,如需转载,请注明出处,否则将追究法律责任。
转载于:http://blog.itpub.net/29876893/viewspace-1839283/