Introduction to Constructors


Objects have a name, member variables, and methods. Before you can use an object in your program, you usually have to create an instance of it. This is done using a constructor. Constructors have the same name as the class they belong to and are preceded by new when called.

Unlike other methods, constructors do not have a return type, but they can receive parameter values. Constructors have been used in Level 0 recipes to create Robot and Random objects, and in Level 1 recipes to create UI objects as shown below:


    new Robot("mini")
    new Random()
    new JFrame()
    new JButton("click me")

Constructors are further explained in the following video: Java Constructors Tutorial



Use a runner class (a class with a main method) to create a Platypus object in your default Java project.

1. First create the Platypus class as shown below.


public class Platypus {
    private String name;
    void sayHi(){
        System.out.println("The platypus " + name + " is smarter than your average platypus.");
    }
}

2. Create another Java class. This will be a "runner" or "driver" class, so it will need a main method.

3. In your runner class, make a new instance of a Platypus

4. Call the sayHi() method - see what happens

5. Create a constructor in the Platypus class that takes a name parameter, so that you can give your Platypus a name.

6. Change your code above to call the new constructor