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 ?
the way I create a reference for
Inner
class object is something like accessingstatic
member inOuter
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();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With