// This example demonstrates why you may want to explicitly // define the default constructor when you write a constructor // for a class. Some important code is commented out here! class Person { // The person class has just a name, and age, and a friend // for each person it it. String name; int age; Person friend; // A constructor for the person class that takes in the // desired initial settings for the person's name, age, // and friend and assigns those values to the appropriate // fields. Person(String n, int a, Person f) { name = n; age = a; friend = f; } // Because a constructor has been defined, the default // constructor no longer exists. Recall that the default // constructor has no behavior; the newly created object // will have the default values in its instance variables // and no computation will have occured. To reintroduce // the default constructor explicitly, uncomment the // following line of code. Java will be able to distinguish // between which of the two constructors to use because // they have different parameter lists; the version of the // constructor that has the appropriate parameter list given // the arguments given to the constructor will be used. // Person(){} // A method to print out the contents of a person object, so // that we can look at the contents. void describe() { System.out.print("name " + name + " age " + age); if (friend == null) System.out.println(" no best friend"); else System.out.println(" friend " + friend.name); return; } } public class Constructor { public static void main(String[] args) { // Create two person objects that you know the name, age, // and friend of; three arguments are passed into the Person // constructor so the first version will be used. Person ann = new Person("Ann", 12, null); Person bob = new Person("Bob", 11, ann); ann.friend = bob; // Create a person object that you do not know any information // about. As the code is now, it will not run and you will get // an error saying: // "No constructor matching Person() found in class Person." // You can correct this by reintroducing the default constructor // (un-comment it out above). Note that this line of code would // have run correctly until the constructor taking parameters // was defined and the default constructor was eliminated. // Once the default constructor has been redefined, it will be // used because no arguments are being passed into the Person // constructor here. Person cary = new Person(); ann.describe(); // prints "name Ann age 12 friend Bob" bob.describe(); // prints "name Bob age 11 friend Ann" cary.describe(); // prints "name null age 0 no best friend" System.out.println("Done!"); // prints "Done!" } }