Today I learnt that you can use the new
operator alongside a separator (.
, or "dot operator"). This made me wonder if Java implicitly uses the same technique for all occurrences of the new operator.
The following statement creates a new "InnerClass object". It does this with a new ParentClass object, using .new
. However, the first new
operator in this statement isn't preceded by a constructor (or an object). So, does Java add one in at compile time? I tried explicitly adding one (Main()
) in to this statement, but the code wouldn't compile.
ParentClass.InnerClass ic = new ParentClass().new InnerClass();
The form
someObject.new InnerClass()
is only used for inner classes. Instances of an inner class must be associated with an instance of their enclosing class. Often, the enclosing instance is this
, negating the need for dotted notation, but when you want to explicitly create an instance of an inner class associated with a different object, the above syntax is what you use.
Most classes in Java are not inner classes. There is no need for an enclosing instance, and thus Java does not implicitly insert new Something()
before all new
calls. (If it did, it would have to insert new Something()
before the calls it inserted, and new Something()
before those, and you couldn't construct anything at all.)