java初学者 问题;希望给我答案

来源:百度知道 编辑:UC知道 时间:2024/05/05 10:06:15
public class Learn10 {
private int age=0;
public Learn10(){ age=1; }
public Learn10(int a){ age=a; }
public int getAge(){return age;}
public void Say(Inner i){
i.Say();
}
public void GO(){
Say(new Inner(){
public void Say(){
System.out.println("ClassName:"+this.getClass().toString());
System.out.println("Age:"+age);//这里没有加this.;不是默认会自动加的吗?但输出确实是Inner的age属性啊
//System.out.println("this.age:"+this.age);
//为什么不能这写,如果这里的this是Inner;那么如何得到Learn10的this引用
}
});
}
public static void main(String[] sr){
new Learn10().GO();
}
}
abstract class Inner{
public Inner(){}
public abstract void Say();
}
现在我想知道怎么才能得到Learn10这个类的this引用;除了用一个变量代替外; 还有其它方法吗?
你们不要只回答我的第一个问题啊

this的两个用途
1、引用隐式参数
2、调用该类其他的构造器

age不属于那两种,所以是会出错的

在main里面:
new Learn10(100).GO();

首先来看,你的Inner中并没有age参数,System.out.println("this.age:"+this.age); 这句话的意思是调用你的内类中的age,这时候的this是Inner的实例对象,但是因为Inner中没有age参数,所以这样写是错的。
再看上面的System.out.println("Age:"+age);这里的age其实是Learn10的age,因为在Main函数中初始化了Learn10,Learn10的构造函数中将age置为1,所以结果才会输出1。
不知道楼主明白了吗?

你这里使用了内部类。