黑马程序员技术交流社区

标题: java入学基础题测试第三题 [打印本页]

作者: 你媚你魅你    时间: 2014-7-28 16:52
标题: java入学基础题测试第三题
在打印语句中如何打印这3个x变量?

class A {
int x = 1;
class B {
int x = 2;
void func() {
int x = 3;
System.out.println( ? );
        }
    }
}
作者: yqj    时间: 2014-7-28 23:24
  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. }
复制代码

不知道对不对,楼主看看吧
作者: 七弟    时间: 2014-7-29 00:03
这是内部类最基本的测试
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);
        }
   
}
作者: zeus00456    时间: 2014-7-29 08:38
将你的?替换成:
x+""+this.x+""+A.this.x
然后主方法中:new A().new B().func();

x是最内层的局部变量
this.x 引用了当前方法(func)所在的实例(B的实例)的成员变量x
A.this.x 引用了A的实例的成员变量x
作者: chen010yu    时间: 2014-7-29 12:23
路过进来学习学习
作者: tommy    时间: 2014-7-29 13:43
进来学习下!!




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