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. }
No return type is listed in front of className.
The return type is automatically a reference to an object of the class.
There is no return
statement in the body of the constructor.
A reference is returned automatically.
(There would be no reason to have a constructor, otherwise.)
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?