I haven't looked at the internals of this but let's first assume the compiler adds an object to proceed new at compile time. That would mean that all our classes are inner classes to another class. Since they are not declared within another class this is not the case. So: no, it does not add something like this at compile time.
Actually, let's break this down.
public class Outer {
String strHello = "Hello ^^";
public void printHello() {
System.out.println(strHello);
}
public static void main(String[] args) {
// This will print: Hello ^^
Outer outer = new Outer();
outer.printHello();
// This will print: Hello ^^
new Outer().printHello();
}
}
I'm guessing you've seen code like this before. It's simply calling a method of the instantiated class. The dot notation can also be used to access variables and inner classes. In the above we have used it to an instance method. Using the keyword static
allows methods and variables to be shared will all instances of the class or even separate classes.
public class Outer {
static String strHello = "Hello ^^";
public static void printHello() {
System.out.println(strHello);
}
static class StaticInner {
}
static class Inner {
}
public static void main(String[] args) {
// Prints: Hello ^^
Outer.printHello();
// Constructs a new Example.StaticInner
Outer.StaticInner inner = new Outer.StaticInner();
// Constructs a new Outer.Inner
Outer.Inner inner = new Example().new Inner();
// Constructs a new Outer.Inner
Example ex = new Example();
Outer.Inner inner = ex.new Inner();
}
}
The above code uses a static inner class to hopefully demonstrate that an inner constructor is just like any other constructor. But, because it's within another class we need to access it through the other (outer) class. It it's not a static inner class then we need to use an instance to access it due to the access modifiers.