Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

explain the way to access inner class in java? [duplicate]

class Outer {    
    class Inner {       

    }    
}

public class Demo {
    public static void main(String args[]) {

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

    }    
}

the way I create a reference for Inner class object is something like accessing static member in Outer class ?
could you please explain the mechanism behind this ?

like image 324
Kalhan.Toress Avatar asked Apr 04 '14 15:04

Kalhan.Toress


1 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 - i.e. following the static syntax:

class Outer {    
    static class Inner {       

    }    
}

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

    }    
}
like image 72
Sergey Kalinichenko Avatar answered Sep 21 '22 03:09

Sergey Kalinichenko