A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 你媚你魅你 初级黑马   /  2014-7-28 16:52  /  1477 人查看  /  6 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

在打印语句中如何打印这3个x变量?

class A {
int x = 1;
class B {
int x = 2;
void func() {
int x = 3;
System.out.println( ? );
        }
    }
}

6 个回复

倒序浏览
  1. class A {
  2.         int x = 1;

  3.         public class B {
  4.                 int x = 2;

  5.                 void func() {
  6.                         int x = 3;
  7.                         System.out.println("A:"+new A().x+"\r\nB:"+this.x+"\r\nfunc:"+x);
  8.             }
  9.         }
  10.        
  11.         public B getB(){
  12.                 return new B();
  13.         }
  14. }
  15. //测试
  16. public class Test3{
  17.         public static void main(String[] args) {
  18.                 A a=new A();
  19.                 A.B b=a.getB();
  20.                 b.func();
  21.         }
  22. }
复制代码

不知道对不对,楼主看看吧
回复 使用道具 举报
这是内部类最基本的测试
class A {
int x = 1;
class B {
int x = 2;
void func() {
int x = 3;
//打印3
System.out.println(x);
//打印2
System.out.println(this.x);
//打印1
System.out.println(new A().x);
System.out.println(A.this.x);
        }
   
}
回复 使用道具 举报
将你的?替换成:
x+""+this.x+""+A.this.x
然后主方法中:new A().new B().func();

x是最内层的局部变量
this.x 引用了当前方法(func)所在的实例(B的实例)的成员变量x
A.this.x 引用了A的实例的成员变量x

点评

赞  发表于 2014-7-29 08:51
回复 使用道具 举报 1 0
路过进来学习学习
回复 使用道具 举报
进来学习下!!
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马