黑马程序员技术交流社区
标题:
求助
[打印本页]
作者:
zhaogang
时间:
2014-3-14 14:05
标题:
求助
在打印语句中如何打印这3个x变量?
class A {
int x = 1;
class B {
int x = 2;
void func() {
int x = 3;
System.out.println( ? );
}
}
}
这个题谁会啊,麻烦写一下正确答案,这个我研究了好几天也没搞懂,主要是我内部类学的不好,希望各位大神指教下,同时说下这个答案的原理,越详细越好,谢谢大家了
作者:
谜燕
时间:
2014-3-14 14:32
class Demo{
public static void main(String[] args){
new A().new B().func();
}
}
class A {
int x = 1;
class B {
int x = 2;
void func() {
int x = 3;
System.out.println( x+"..."+this.x+"..."+A.this.x);
}
}
}
复制代码
如果类A的成员变量x是静态的,用A.x表示。
作者:
往事如烟
时间:
2014-3-14 14:58
楼主你这是局部变量的作用域和类成员变量的访问没搞明白,
package com.itheima;
class A
{
int x = 1;//作用域是A
class B {
int x = 2; //作用域在B
void func() {
int x = 3; //作用域在func方法
System.out.println("func:"+x);// x 表示当前方法func的 int x
System.out.println(" B:"+this.x);//this.x 表示 当前类B的int x
System.out.println(" A:"+A.this.x);// A.this.x:表示A类的int x
}
}
public static void main(String[] args)throws Exception {
new A().new B().func();
}
}
复制代码
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2