Where in the above code is a constructor being used?
HelloObject anObject = new HelloObject("A Greeting!");
What is its parameter? A reference to the string, "A Greeting!"
The class needs a constructor. Constructor definitions look like this:
className( parameterList ) { Statements involving the variables of the class and the parameters in the parameterList. }
A constructor always returns a reference to the object it constructs.
Don't put a return type in front of className and
don't use a return
statement in the body of the constructor.
The constructor has the same name as the class. The parameterList is a list of values and their types:
TypeName1 parameterName1, TypeName2 parameterName2, ... as many as you need
It is OK to have an empty parameter list. A class often has several constructors with different parameters. Each one builds the same class of object, but the different constructors use different sources of data for object initialization.
Usually the method that invokes a constructor saves the returned reference in a variable. But sometimes an object is constructed for temporary use and its reference is not saved. The object is used once for some brief purpose and then becomes garbage.
Can a parameter be an object reference?
Can a parameter be a primitive data type?