黑马程序员技术交流社区
标题:
内部类引用外部类的成员变量
[打印本页]
作者:
不愿一人
时间:
2013-12-22 16:23
标题:
内部类引用外部类的成员变量
其他地方不给回复,还是来着吧,求大神指点啊
这是我在黑马做基础测试时遇到的,对于func中的x直接访问就可以
对于B类中的成员变量x,用this.x
但对A类中的成员变量,应该怎么访问啊
class A {
int x = 1;
class B {
int x = 2;
void func() {
int x = 3;
System.out.println( ? );
}
}
}
作者:
刘旭升
时间:
2013-12-22 18:26
你看看这两句话对你有没有帮助:内部类可以直接调用外嵌类的方法和成员变量。其中外嵌类把内部类的对象看成是自己的成员,貌似你上面的程序没有调用呢。
作者:
天天学习
时间:
2013-12-22 18:46
class Outer
{
private int x = 3;
class Inner
{
private int x = 4;
void function()
{
int x = 5;
System.out.println("x="+x);
System.out.println("tis.x="+this.x);
System.out.println("Outer.this.x="+Outer.this.x);
}
}
}
class InnerClass
{
public static void main(String[] args)
{
Outer.Inner in = new Outer().new Inner();
in.function();
}
}
复制代码
打印结果为: x=5,this.x=4,Outer.this.x=3;由此可知:x为内部类局部变量,this.x为内部类成员变量而Outer.this.x为外部类成员变量
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2