返回信息流class Outer {
private int index=100;
class Inner {
private int index = 50;
void print() {
int index = 30;
System.out.println(index);
System.out.println(this.index);
System.out.println(Outer.this.index);// 请问这里为什么不能直接用Outer.index呢?编译器会提示静态引用一个非静态变量错误。通过this访问为啥就算静态的了呢?
}
}
void print() {
Inner inner = new Inner();
inner.print();
}
}
class Test {
public static void main (String[] argv) {
Outer outer = new Outer();
outer.print();
}
}
多谢各位。
这是一条镜像帖。来源:北邮人论坛 / java / #19637同步于 2011/8/7
该镜像源已超过 30 天没有更新,可能在源站已被删除。
Java机器人发帖
【求助】静态引用非静态变量错误
kelvin4617
2011/8/7镜像同步12 回复
订阅后,新回复会通过你的通知中心匿名送达。
9 条回复
thinking in java:
如果你需要生成对外部类的引用,可以使用外部类的名字后面紧跟圆点和this。这样产生的引用自动地具有正确的类型,这一点在编译期就被知晓并受到检查,因此没有任何运行时开销。
另外,如果不加this的话,Outer.index 是引用Outer的静态变量,而你的index木有声明成static
没问题啊
我这编译通过,可以运行
public class Outer {
public static void main(String args[]){
Outer outer = new Outer();
outer.print();
}
private int index = 100;
class Inner {
private int index = 50;
void print() {
int index = 30;
System.out.println(index);
System.out.println(Inner.this.index);
System.out.println(Outer.this.index);
}
}
void print() {
Inner inner = new Inner();
inner.print();
}
}
【 在 kelvin4617 (留守儿童) 的大作中提到: 】
: class Outer {
: private int index=100;
: class Inner {
: ...................
多谢,就是疑惑为啥使用this引用的话index就不用声明成static。看来就是这么个机制,通过this就总是可以引用外部类了是吧。
【 在 ingenious 的大作中提到: 】
: thinking in java:
: 如果你需要生成对外部类的引用,可以使用外部类的名字后面紧跟圆点和this。这样产生的引用自动地具有正确的类型,这一点在编译期就被知晓并受到检查,因此没有任何运行时开销。
: 另外,如果不加this的话,Outer.index 是引用Outer的静态变量,而你的index木有声明成static
: ...................
嗯嗯 多谢,这段是可以运行的,像注释里边那样写就会出错~
【 在 ox 的大作中提到: 】
: 没问题啊
: 我这编译通过,可以运行
: public class Outer {
: ...................
多谢,这个是看孙鑫的java视频里边的一段示例代码,他一开始就直接用Outer.this.index,也没说原因,然后自己不太明白为啥不能用Outer.index,试了试编译不能通过,就来版上求指导了。
【 在 JacKie575 的大作中提到: 】
: 请问哪本书里面给出这种示例的?
: 如果考虑可读性的话,真的没什么好说的。。
: --
: ...................
多谢,可是this不也不是具体的实例么?
【 在 yqiao2007 的大作中提到: 】
: 因为index不是静态常量,必须依附于一个具体的对象而存在,我觉得是这样子的
: --