package com.ithe;
import org.junit.Test;
/**
* 8、 在打印语句中如何打印这3个x变量?
class A {
int x = 1;
class B {
int x = 2;
void func() {
int x = 3;
System.out.println( ? );
}
}
}
*解析:
* Java关键字this只能用于方法方法体内。当一个对象创建后,Java虚拟机(JVM)就会给这个对象分配一个引用自身的指针,这个指针的名字就是 this。因此,
*this只能在类中的非静态方法中使用,静态方法和静态的代码块中绝对不能出现this,这在“Java关键字static、final 使用总结”一文中给出了明确解释。
*并且this只和特定的对象关联,而不和类关联,同一个类的不同对象有不同的this。
*/
public class Test8 {
public static void main(String[] args) {
Test8 test= new Test8();
A a = test.getA();
A.B b = a.new B();
b.func();
}
private A getA(){
return new A();
}
class A {
int x = 1;
class B {
int x = 2;
void func() {
int x = 3;
System.out.println("从最外层到最里层x的值分别为:"+A.this.x+","+this.x+","+x);
// A.this.x表示 A类对象的x属性
// this.x 表示本类对象的x属性
// x在这里被新定义的值覆盖
}
}
}
}
import org.junit.Test;
/**
* 8、 在打印语句中如何打印这3个x变量?
class A {
int x = 1;
class B {
int x = 2;
void func() {
int x = 3;
System.out.println( ? );
}
}
}
*解析:
* Java关键字this只能用于方法方法体内。当一个对象创建后,Java虚拟机(JVM)就会给这个对象分配一个引用自身的指针,这个指针的名字就是 this。因此,
*this只能在类中的非静态方法中使用,静态方法和静态的代码块中绝对不能出现this,这在“Java关键字static、final 使用总结”一文中给出了明确解释。
*并且this只和特定的对象关联,而不和类关联,同一个类的不同对象有不同的this。
*/
public class Test8 {
public static void main(String[] args) {
Test8 test= new Test8();
A a = test.getA();
A.B b = a.new B();
b.func();
}
private A getA(){
return new A();
}
class A {
int x = 1;
class B {
int x = 2;
void func() {
int x = 3;
System.out.println("从最外层到最里层x的值分别为:"+A.this.x+","+this.x+","+x);
// A.this.x表示 A类对象的x属性
// this.x 表示本类对象的x属性
// x在这里被新定义的值覆盖
}
}
}
}