黑马程序员技术交流社区

标题: 在打印语句中如何打印这3个x变量?疑问 [打印本页]

作者: 实战造就实力    时间: 2014-1-1 16:33
标题: 在打印语句中如何打印这3个x变量?疑问
本帖最后由 实战造就实力 于 2014-1-4 18:56 编辑

怎么在主函数中运行啊 ?帮忙解答。

class A {
int x = 1;

class B {
    int x = 2;

    void func() {
        int x = 3;
        System.out.println( ? );
    }
}
}


作者: 由然自美    时间: 2014-1-1 16:36
System.out.println("func中x="+x);
System.out.println("内部类x="+this.x);
System.out.println("外部类x="+A.this.x);
作者: 实战造就实力    时间: 2014-1-1 16:45
由然自美 发表于 2014-1-1 16:36
System.out.println("func中x="+x);
System.out.println("内部类x="+this.x);
System.out.println("外部类x ...

怎么在主函数中运行啊
作者: 程玉习    时间: 2014-1-1 17:02
建立对象调用就可以了,下面是用匿名对象调用的
  1. class Test
  2. {
  3.         public static void main(String[] args)
  4.         {
  5.                 System.out.println(new A().x);
  6.                 System.out.println(new B().x);
  7.                 new B().run();
  8.         }
  9. }

  10. class A
  11. {
  12.         int x = 1;
  13. }

  14. class B
  15. {
  16.         int x = 2;

  17.         void run()
  18.         {
  19.                 System.out.println("keyi");
  20.         }
  21. }
复制代码

作者: daoyua    时间: 2014-1-1 17:09
楼上正解
作者: 小悠久    时间: 2014-1-3 22:15
public class Test {
         * @param args
         */
       
        public static void main(String[] args) {
                //调用内部类B
                A.B d=new A().new B();
        d.func();  
        }

         static class A {
            int x = 1;
            class B {
                int x = 2;
         
                void func() {
                    int x = 3;
                    System.out.println( A.this.x + "," +  B.this.x + "," + x);
                }
            }
        }
}
作者: 小悠久    时间: 2014-1-3 22:16
public class Test {
         * @param args
         */
       
        public static void main(String[] args) {
                //调用内部类B
                A.B d=new A().new B();
                                       d.func();  
        }

         static class A {
            int x = 1;
            class B {
                int x = 2;
         
                void func() {
                    int x = 3;
                    System.out.println( A.this.x + "," +  B.this.x + "," + x);
                }
            }
        }
}




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