java inner/outer class questions about outer class private variables access

后端 未结 2 580
自闭症患者
自闭症患者 2020-12-29 07:32

I have the following java class:

class Outer
{
    private Integer a;
    private Long b;

    class Inner
    {
        public void foo()
        { 
                


        
相关标签:
2条回答
  • 2020-12-29 08:17

    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.

    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.

    Edit: 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.

    0 讨论(0)
  • 2020-12-29 08:20

    1) They have to be static, in order to not be overridden in some sub class. I hope you understand.

    <Addendum>

    Shrini, from your comment, it seems that there is a need to explain the things to avoid some misconceptions. First of all, know on thing that static methods can not be overridden. Overriding is exclusive in objects, and it is there to facilitate polymorphism. Whereas static methods belongs to the class. Found a couple of good resources to support my argument and for you to understand that static methods can not be overridden.

    • Can you override static methods in Java
    • Why static methods can't be abstract

    Now for your second retort, you are right in saying that they have package level access and can't be overridden in subclasses outside the package. But I don't know why are you neglecting the case where subclass/es exist in the same package. Its a valid case, IMO. In fact, it would be absurd to name a method like access$000() or something like that, in a real work. But don't underestimate the chance of accidental overriding. There can be a case where the subclass of Outer, say SubOuter, has an inner class of itself too. I didn't try to javap that case myself, just guessing.

    </Addendum>

    2) Even if you think it will not get modified, technically there is a possibility as cletus pointed out already, use of final can provide easy optimizations by the compiler.

    0 讨论(0)
提交回复
热议问题