class wai{
private int x=10;
public void show(){
final int x=20;
class nei{
int x=30;
public void method(){
System.out.println("x="+x);//这个地方如何打印出变量x的等于20的值呢(如打印x为10的值:wai.this.x,如果打印x等于30的值:x,那如果打印x等于20的值呢,该如何写呢)
}
}
nei n=new nei();
n.method();
}
}class neiwai{
public static void main(String args[]){
wai y=new wai();
y.show();
}
}
private int x=10;
public void show(){
final int x=20;
class nei{
int x=30;
public void method(){
System.out.println("x="+x);//这个地方如何打印出变量x的等于20的值呢(如打印x为10的值:wai.this.x,如果打印x等于30的值:x,那如果打印x等于20的值呢,该如何写呢)
}
}
nei n=new nei();
n.method();
}
}class neiwai{
public static void main(String args[]){
wai y=new wai();
y.show();
}
}
demo1.java:8: 错误: 找不到符号
System.out.println("x="+show.this.x);
^
符号: 类 show
位置: 类 nei
1 个错误
class Test{
private int x=10; //成员变量
static int y=20;//或者这样写
public void show(){
final int x=20;//方法中定义的局部常量
System.out.println("x="+x);// x=20
class nei{ //内部类可以定义自己的属性和方法
int x=30;
public void method(){
System.out.println("y="+Test.y);//引用静态变量 y=20
System.out.println("x="+Test.this.x);//指的是指定对象对象(Test)的成员变量. x=10
System.out.println("x="+this.x);//指的是当前对象(nei)的成员变量和 System.out.println("x="+x);的效果是一样的. x=30
}
}
nei n=new nei();
n.method();
}
public static void main(String args[]){
Test y=new Test();
y.show();
}
}
所以这个地方直接改成System.out.println("x="+wai.this.x);
private int x=10;
public void show()
{
final int x=20;
class nei
{
int x=30;
public void method()
{
System.out.println("x="+wai.this.x);
//这个地方如何打印出变量x的等于20的值呢(如打印x为10的值:wai.this.x,如果打印x等于30的值:x,那如果打印x等于20的值呢,该如何写呢)
}
}
nei n=new nei();
n.method();
}
}
public class neiwai
{
public static void main(String args[])
{
wai y=new wai();
y.show();
}
}
既然楼主在show() 方法里把x定义成了final了,就是想在方法里的局部内部类里使用,这时对内部类来说,都存在这个x的一个拷贝,其值就是20。而如果楼主这时在类里重新定义了 x,则把类里的拷贝过来的那个x(20)覆盖了。
只要不覆盖这个x,那么它就一直可用。楼主可以把内部类里的变量,换个名字。或先输出,后在方法里覆盖。class Wai1
{
private int x=10;
public void show()
{
final int x=20;
//内部类Nei1,不覆盖方法里的变量x.
class Nei1
{
int y=30;
public void method1()
{
System.out.println("x in class Wai ="
+Wai1.this.x+"\r\nx in method show()= "+x);
System.out.println("y in method ="+y);
}
}
//内部类2,把内部类里的变量挪到方法里面,先输出后覆盖。
class Nei2
{
public void method2()
{
System.out.println("x in class Wai ="
+Wai1.this.x+"\r\nx in method show()= "+x);
int x=30;
System.out.println("x in method ="+x);
}
}
Nei1 n1=new Nei1();
n1.method1();
Nei2 n2=new Nei2();
n2.method2();
}
}
class Neiwai1
{
public static void main(String args[])
{
Wai1 y=new Wai1();
y.show();
}
}结果:
x in class Wai =10
x in method show()= 20
y in method =30
x in class Wai =10
x in method show()= 20
x in method =30