Wednesday 2 October 2013

Java super constructor execution sequence

Java super constructor execution sequence

I've been studying from the Java Certification Bates and Sierra book and
am stumped on chapter 2 constructor explanation:
public class Animal {
String name;
Animal(String name) {
super();
{System.out.println("Hello");} //I put this in myself
this.name = name;
}
Animal() {
this(makeRandomName());
}
static String makeRandomName() {
int x = (int) (Math.random() * 5);
String name = new String[] {"Fluffy", "Fido",
"Rover", "Spike",
"Gigi"}[x];
return name;
}
public static void main (String [] args) {
Animal a = new Animal();
System.out.println(a.name);
Animal b = new Animal("Zeus");
System.out.println(b.name);
}
}
The following is from the Bates and Sierra book:
"Notice that the makeRandomName() method is marked static! That's because
you cannot invoke an instance (in other words, nonstatic) method (or
access an instance variable) until after the super constructor has run.
And since the super constructor will be invoked from the constructor on
line 3, rather than from the one on line 7, line 8 can use only a static
method to generate the name."
I did an experiment and I inserted a super call in the overloaded
constructor and my results were:
Hello Rover Hello Zeus
Now from these results, it seems as though the overloaded constructor AND
the super constructor is executed before the static method because Hello
prints before Zeus and Rover. So, why is there a need for a static
variables?
What am I missing?
Thanks, Jane

No comments:

Post a Comment