外部類的this關(guān)鍵字用法
package two.com;
public class Demo02 {//外部類
public void show(){
System.out.println("你好!");
}
public class Demo002{//內(nèi)部類
public void show(){
System.out.println("nihao!");
}
}
public static void main(String[] args) {
Demo02 hello=new Demo02();
Demo002 hello2=hello.new Demo002();
hello.this.show();
}
}
最后的hello.this.show();不對 ? ?請問應(yīng)該怎么改正?
2016-10-25
在main方法里想調(diào)用內(nèi)部類的方法直接用 hello2.show();即可,想調(diào)用外部類的方法直接用hello.show();
這里你的意思估計是想在內(nèi)部類中 調(diào)用外部類的方法,用法是Demo02.this.show();
具體代碼如下:
public class Demo02 {// 外部類
public void show() {
System.out.println("你好!");
}
public class Demo002 {// 內(nèi)部類
public Demo002(){
Demo02.this.show();
}
public void show() {
System.out.println("nihao!");
}
}
public static void main(String[] args) {
Demo02 hello = new Demo02();
Demo002 hello2 = hello.new Demo002();
/*hello.show();
hello2.show(0;
*/
}
2016-10-25
this代表的是對象,this.方法()代表對象的方法。所以前面不用加對象名。你這里直接去掉this即可。
2016-10-25
首先this必須要放在方法中第一行才符合規(guī)范。還有你前面兩個方法的規(guī)則也不對,語法沒錯,但是使用規(guī)則不對當然就不能用,首先你要理解this的概念,this的意思是方法中包含一個參數(shù),本類中有一個屬性的名稱和參數(shù)是一樣的,避免混淆才使用this區(qū)分開。 ?你這里不存在這種情況,所以不需要使用this