Can a nonstatic member type be used without association with an instance of the enclosing class?
For example
class Outer {
class Inner {
}
}
public class Demo {
public static void main(String args[]) {
Outer o = new Outer();
Outer.Inner inner = o.new Inner();
}
}
In Outer.Inner inner = o.new Inner()
, does Outer.Inner
use Inner
without association to an instance of the enclosing class?
Is there other example where a nonstatic member type can be used without association with an instance of the enclosing class?
Thanks
does
Outer.Inner
useInner
without association to an instance of the enclosing class?
In a sense, yes, because Outer.Inner
refers to a type. And you never need instances in order to use types.
I think you mistakenly thought that Outer.Inner
shouldn't work because there are an infinite number of different types called Inner
, created with different instances of Outer
. You might have thought that if I have two different instances of Outer
, o1
and o2
, they will create different Inner
types.
But this is entirely not true. You can totally do something like this:
Outer o1 = new Outer();
Outer o2 = new Outer();
Outer.Inner inner1 = o1.new Inner();
Outer.Inner inner2 = o2.new Inner();
inner2 = inner1;
So Outer.Inner
is just one type. It just so happens to be that an instance of this type requires an instance of Outer
in order to be created.