Defining Constructors
In this lesson, we will look at the types of constructors and how they are defined within a Java class.
We'll cover the following...
The default constructor
The definition of any constructor begins with the access modifier public
, the name of the class—which is the name of the constructor—and a pair of parentheses. Nothing appears between these parentheses for a default constructor. For example, the definition of the default constructor for the class Greeter
is
/** Creates a default Greeter object. */
public Greeter()
{
greeting = "Hello, world!";
} // End default constructor
Let’s recall how we used the class Greeter
in the first lesson of this chapter:
/** GreeterDemo.java by F. M. CarranoDemonstrates the class Greeter.*/public class GreeterDemo{public static void main(String args[]){Greeter standardWelcomer = new Greeter();Greeter townCrier = new Greeter("It's 12 o'clock; all is well!");Greeter courtClerk = new Greeter("Order in the Court!");standardWelcomer.greet();townCrier.greet();courtClerk.greet();} // End main} // End GreeterDemo
We see that the statement
Greeter standardWelcomer = new Greeter();
creates a Greeter
object and invokes the default constructor. Memory space is allocated for the new object, including space for a string called greeting
. This memory allocation happens without any effort on our part. Thus, the new object has its own data field, or instance variable, greeting
, that is a string, as shown in ...