explain the way to access inner class in java?

This question already has an answer here:

  • Java inner class and static nested class 23 answers

  • the way I create a reference for Inner class object is something like accessing static member in Outer class

    Not at all - since you are using an instance of the Outer to access the constructor of the Inner , this is very much like accessing an instance member of the Outer class, not its static member. The name of the Inner class in the declaration is qualified with the name of its outer class Outer in order to avoid naming conflicts with top-level classes.

    The reason for that is easy to understand: Inner is a non-static inner class, so it needs to reference an Outer . It does so implicitly, but the reference must be passed to the constructor behind the scene. Therefore, you call a constructor of Inner on an instance of Outer .

    The syntax for making instances of static classes is similar to the syntax for making instances of regular classes, except the name of the nested class must be prefixed with the name of its outer class - ie following the static syntax:

    class Outer {    
        static class Inner {       
    
        }    
    }
    
    public class Demo {
        public static void main(String args[]) {
            Outer.Inner inner = new Outer.Inner();    
    
        }    
    }
    

    You're actually accessing an inner class in a non-static way. A static inner class is actually different - the compiler makes a top-level class for it that is hidden from the programmer, which then works similarly to the way of instantiation that you have posted for the inner class.

    You have to declare this way because since the inner class is non-static, it needs an instance of the outer class to make an instance of the inner class.

    Outer o = new Outer(); 
    

    is the required instance for the outer class.

    Outer.Inner inner = o.new Inner(); 
    

    is required for the instance of the inner class.


    Not sure exactly what you are asking, but your code is valid.

    You can only instantiate Inner if you have an instance of Outer, so you call only call Inner's constructor in the context of an instance of Outer, hence

    Outer o = new Outer();
    Inner i = o.new Inner();
    

    works, but

    Inner i = new Outer.Inner(); //bad
    Inner i = Outer.new Inner(); //bad
    

    are both trying to access Inner in a static way, and will not compile.

    If you want create instances of Inner without first creating an instance of Outer, then Inner needs to be static

    链接地址: http://www.djcxy.com/p/92008.html

    上一篇: java中'new'的语法

    下一篇: 解释在java中访问内部类的方式?