国科控股董事长的级别:java中的this关键字

来源:百度文库 编辑:神马品牌网 时间:2024/04/25 14:26:06
this引用句柄
一个对象中的一个成员方法,可以引用另外一个对象的成员。
class A{
String strName;
public A(String x){
name = x;
}
public void func1(){
System.out.println("func1 of " + name + " is calling");
}
public void func2(){
A a2 = new A("a2");
this.func1();
a2.func1();
}
}
class TestA{
public static void main(String args[]){
A a1 = new A("a1");
a1.func2();
}
}
Result:
func1 of a1 is calling.
func2 of a2 is calling.
this关键字在Java程序里的作用和它的词义很接近,它在函数内部就是这个函数所属的对象的引用变量。

这里的this.func1();到底是什么意思 我研究了N次都不知道什么意思.郁闷死 我怎么这么笨...

this.func1();代表这个类当前对象(说白了就是类本身,JAVA在类定义里默认一个对象代表类本身行驶调用方法的功能)引用这个方法
a1.func2(); 就是这个具体对象调用方法

不写this,直接用func1()效果是一样的

不写this

本类生成的当前对象

结果肯定错了,func2 of a2 is calling.这句话应该是func1 of a2 is calling.
首先弄明白this是什么意思就可以了明白了
this是返回当前对象的引用,这个关键词经常出现,和super一样,super返回父类对象的引用.
class TestA{
public static void main(String args[]){
A a1 = new A("a1");
a1.func2();
}
} 这里的a1.func2();相当于a1.func1();
a2.func1();