A constructor can be thought of as a specialized method of a class that creates (instantiates) an instance of the class and performs any initialization tasks needed for that instantiation. The sytnax for a constructor is similar but not identical to a normal method and adheres to the following rules:
- The name of the constructor must be exactly the same as the class it is in.
- Constructors may be private, protected or public.
- A constructor cannot have a return type (even void). This is what distinguishes a constructor from a method. A typical beginner's mistake is to give the constructor a return type and then spend hours trying to figure out why Java isn't calling the constructor when an object is instantiated.
- Multiple constructors may exist, but they must have different signatures, i.e. different numbers and/or types of input parameters.
- The existence of any programmer-defined constructor will eliminate the automatically generated, no parameter, default constructor. If part of your code requires a no parameter constructor and you wish to add a parameterized constructor, be sure to add another, no-parameter constructor.
Example
public Person {
private String name;
public Person(String name) {
_name = name;
}
}
The above code defines a public class called Person with a public constructor that initializes the _name field.
To use a constructor to instantiate an instance of a class, we use the new keyword combined with an invocation of the constructor, which is simply its name and input parameters. new tells the Java runtime engine to create a new object based on the specified class and constructor. If the constructor takes input parameters, they are specified just as in any method. If the resultant object instance is to be referenced by a variable, then the type of the newly created object must be of the same type as the variable. (Note that the converse is not necessarily true!). Also, note that an object instance does not have to be assigned to a variable to be used.
Example
Person me = new Person("Stephen");
The above code instantiates a new Person object where _namefield has the value "Stephen".
- 2008 reads