Let’s look at the following code snippet in Java.
package trickyjava;
class A
{
public A(String s)
{
System.out.println(s);
}
}
final class B extends A
{
public B()
{
super(method()); // Calling the following method first.
}
private static String method()
{
return "method invoked";
}
}
final public class Main
{
public static void main(String[] args)
{
B b = new B();
}
}
By convention, the super() constructor in Java must be the first statement in the relevant constructor body. In the above code, we are calling the static method in the super() constructor parameter list itself super(method());.
It means that in the call to super in the constructor B(), a method is being
called BEFORE the call to super is made! This should be forbidden by the compiler but it works nice. This is somewhat equivalent to the following statements.
String s = method();
super(s);
However, it’s illegal causing a compile-time error indicating that “call to super must be first statement in constructor”. Why? and why it’s equivalent super(method()); is valid and the compiler doesn’t complain any more?
The key thing here is the
staticmodifier. Static methods are tied to the class, instance methods (normal methods) are tied to an object (class instance). The constructor initializes an object from a class, therefore the class must already have been fully loaded. It is therefore no problem to call a static method as part of the constructor.The sequence of events to load a class and create an object is like this:
(simplified*)
By the time the object constructor is called, the static methods and variables are available.
Think of the class and its
staticmembers as a blueprint for the objects of that class. You can only create the objects when the blueprint is already there.The constructor is also called the initializer. If you throw an exception from a constructor and print the stack trace, you’ll notice it’s called
<init>in the stack frame. Instance methods can only be called after an object has been constructed. It is not possible to use an instance method as the parameter for thesuper(...)call in your constructor.If you create multiple objects of the same class, steps 1 and 2 happen only once.
(*static initializers and instance initializers left out for clarity)