java面向对象-内部类的访问规则

/*
内部类的访问规则:
1,内部类可以直接访问外部类中的成员,包括私有
    之所以可以直接访问外部类中的成员,是因为了内部类中持有了一个外部类的引用,格式:外部类名.this
2,外部类要访问内部类,必须建立内部类对象
*/
 
class Outer
{
    private int x = 3;
    class Inner//内部类
    {
        int x = 4;
        void function()
        {
            int x = 6;
            System.out.println("inner:"+x);//6
            System.out.println("inner:"+this.x);//4
            System.out.println("inner:"+Outer.this.x);//3
        }
    }
    void method()
    {
        Inner in = new Inner();
        in.function();
    }
}
 
class InnerClassDemo
{
    public static void main(String[] args)
    {
        // Outer out = new Outer();
        // out.method();
         
        //直接访问内部类中的成员
        Outer.Inner in = new Outer().new Inner();
        in.function();
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值