java内部/外层类关于外层类的私有变量访问 [英] java inner/outer class questions about outer class private variables access

查看:184
本文介绍了java内部/外层类关于外层类的私有变量访问的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下的java类:

I have the following java class:

class Outer
{
    private Integer a;
    private Long b;

    class Inner
    {
        public void foo()
        { 
            System.out.println("a and b are " + a + " " + b);
        }
    }
}

和外部$ Inner,我得到以下:

when I run javap on Outer and Outer$Inner, I get the following:

C:\test>javap Outer
Compiled from "Outer.java"
class Outer extends java.lang.Object{
    Outer();
    static java.lang.Integer access$000(Outer);
    static java.lang.Long access$100(Outer);
}

C:\test>javap Outer$Inner
Compiled from "Outer.java"
class Outer$Inner extends java.lang.Object{    
    final Outer this$0;
    Outer$Inner(Outer);
    public void foo();
}

我有两个问题:

1)为什么java编译器生成静态方法,在外部类中使用Outerparam来访问它的私有变量?为什么不是内部类可以很容易地通过其$ 0成员调用的实例方法?

1) why does java compiler generate static methods that take 'Outer' param, in the outer class, for accessing its private variables ? why not instance methods that the inner class can easily call through its this$0 member ?

2)为什么这个$ 0在内部类最终?

2) why is this$0 in inner class made final ? what will happen if it is not final ?

推荐答案

如果不是最终的话,会发生什么?

解决方案

非静态内部类具有对外部类的实例的隐式引用。这被实现为对外部类的 final 引用。如果它不是 final ,技术上可以在实例化后修改。

Non-static inner classes have an implicit reference to an instance of the outer class. This is implemented as a final reference to the outer class. If it wasn't final technically it could be modified after instantiation.

外层类被隐式传递,是为什么内部类上的任何构造函数都有外部类的隐式参数,这是如何传递 this $ 0

The outer class is implicitly passed in which is why any constructors on the inner class have an implicit parameter of the outer class, which is how this$0 is passed in.

修改访问$ 000 方法的关键线索是他们是包访问,他们采取 Outer 作为参数。因此,当 Inner 中的代码调用时,例如 Inner.this.a ,它实际上调用 Inner .access $ 000(this $ 0)。所以这些方法有访问 private 外部类的成员到内部类。

as for the access$000 methods the key clue is that they're package access and they take an Outer as an argument. So when code in Inner calls, say, Inner.this.a it's actually calling Inner.access$000(this$0). So those methods are there to give access to private members of the outer class to the inner class.

这篇关于java内部/外层类关于外层类的私有变量访问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆