当内部类和外部类存在同名成员时,如何访问外部类的成员

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了当内部类和外部类存在同名成员时,如何访问外部类的成员相关的知识,希望对你有一定的参考价值。

打印结果是什么 答案2
public class Test {

public static void main(String[] args) {
    Outer.Inner on = new Outer().new Inner();
    on.function();
}

}

class Outer {
int x = 0 ;
class Inner{
int x = 1;
void function(){
int x =2;
System.out.println("x="+x);
}
}
}
上述程序如何访问内部类的成员变量
public class Test {

public static void main(String[] args) {
    Outer.Inner on = new Outer().new Inner();
    on.function();
}

}

class Outer {
int x = 0 ;
class Inner{
int x = 1;
void function(){
int x =2;
System.out.println("x="+this.x);
}
}
}
如何访问外部类的成员变量
public class Test {

public static void main(String[] args) {
    Outer.Inner on = new Outer().new Inner();
    on.function();
}

}

class Outer {
int x = 0 ;
class Inner{
int x = 1;
void function(){
int x =2;
System.out.println("x="+Outer.this.x);
}
}
}

以上是关于当内部类和外部类存在同名成员时,如何访问外部类的成员的主要内容,如果未能解决你的问题,请参考以下文章

成员内部类的优点

内部类和 外部类相互访问

Java 内部类及其原理

java 内部类和外部类的关系

内部类学习

内部类和外部类之间的相互调用