Thinking in Java Fourth Edition Bruce Eckel Chapter 6 Exercise 1

Exercise 1: Create a simple class. Inside a second class, define a reference to an object of the first class. Use lazy initialization to instantiate this object.

class Engine
{
    private String s;
    Engine()
    {
        System.out.println("Engine()");
        s = "Constructed";
    }
    public String toString()
    {
        return s;
    }
}

public class Airplane
{
    private String fuselage, wings, tail;
    private Engine e;
    public Airplane()
    {
        System.out.println("Inside Airplane()");
        fuselage = "Body";
        wings = "Airfoils";
        tail = "Empennage";            
    }
    public String toString()
    {
        if(e == null) // lazy (delayed) initialization:
            e = new Engine();
        return "fuselage = " + fuselage + ", " +
            "wings = " + wings + ", " +
            "tail = " + tail + ", " +
            "Engine = " + e;
    }
    public static void main(String[] args)
    {
        Airplane N1234 = new Airplane();
        System.out.println(N1234);
    }
}

Output:

One Reply to “Thinking in Java Fourth Edition Bruce Eckel Chapter 6 Exercise 1”

Leave a Reply

Your email address will not be published. Required fields are marked *