Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Order of execution in Java

I am trying to understand this example from Thinking in Java:

package c07;
import com.bruceeckel.simpletest.*;

class Meal {
    Meal() { System.out.println("Meal()"); }
}

class Bread {
    Bread() { System.out.println("Bread()"); }
}

class Cheese {
    Cheese() { System.out.println("Cheese()"); }
}

class Lettuce {
    Lettuce() { System.out.println("Lettuce()"); }
}

class Lunch extends Meal {
    Lunch() { System.out.println("Lunch()"); }
}

class PortableLunch extends Lunch {
    PortableLunch() { System.out.println("PortableLunch()");}
}

public class Sandwich extends PortableLunch {
    private static Test monitor = new Test();
    private Bread b = new Bread();
    private Cheese c = new Cheese();
    private Lettuce l = new Lettuce();

    public Sandwich() {
        System.out.println("Sandwich()");
    }

    public static void main(String[] args) {
        new Sandwich();
        monitor.expect(new String[] {
          "Meal()",
          "Lunch()",
          "PortableLunch()",
          "Bread()",
          "Cheese()",
          "Lettuce()",
          "Sandwich()"
        });
    }
}

As I understand from Java Language Specification, the order of execution begins by loading the class containing the main method. Then all the statics and member variables of this class must be initialized (before which all the member variables of the superclasses must be intialized, although there are none of those in this case).

So I thought b, c, l would be initialized before main starts executing. That does not seem to be the case from the output though. Am I missing something?

like image 384
Jin Avatar asked Oct 02 '12 18:10

Jin


1 Answers

No, b and c are instance variables.

There's no automatic instantiation of the class containing main. Only static variables are initialized. It's just as if some outside caller wrote:

Sandwich.main(args);

So when you wrote:

Then all the statics and member variables of this class must be initialized

... that was wrong. Only the static variables are initialized - just as normal.

like image 96
Jon Skeet Avatar answered Sep 19 '22 04:09

Jon Skeet