黑马程序员技术交流社区

标题: 求助 [打印本页]

作者: 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
  1. class Demo{
  2. public static void main(String[] args){
  3.         new A().new B().func();
  4. }
  5. }
  6.         class A {
  7.             int x = 1;

  8.             class B {
  9.                 int x = 2;

  10.                 void func() {
  11.                     int x = 3;
  12.                     System.out.println( x+"..."+this.x+"..."+A.this.x);
  13.                 }
  14.             }
  15.         }
复制代码

如果类A的成员变量x是静态的,用A.x表示。
作者: 往事如烟    时间: 2014-3-14 14:58
楼主你这是局部变量的作用域和类成员变量的访问没搞明白,
  1. package com.itheima;
  2. class A
  3. {
  4.             int x = 1;//作用域是A
  5.             class B {
  6.                int x = 2; //作用域在B
  7.                void func() {
  8.                     int x = 3; //作用域在func方法
  9.                     System.out.println("func:"+x);// x 表示当前方法func的 int x
  10.                     System.out.println(" B:"+this.x);//this.x  表示 当前类B的int x
  11.                     System.out.println(" A:"+A.this.x);// A.this.x:表示A类的int x
  12.                    
  13.                 }
  14.             }
  15.             
  16.         public static void main(String[] args)throws Exception {
  17.                 new A().new B().func();
  18.         }
  19. }
复制代码





欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2