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

本文提供了一个Java程序示例,展示了如何在内部类的方法中访问局部变量、内部类成员变量及外部类成员变量。通过使用this关键字指定当前类的成员变量及外部类的this关键字来明确地访问外部类成员。

打印结果是什么 答案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);
        }
    }
}

转载于:https://blog.51cto.com/13579086/2065943

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值