Constructor Definition Syntax

Classic programmed-learning exercises, refreshed for modern Java and presented in the current MrStyner.com portfolio style.

Modern Java noteThis archive has been refreshed for Java 25 LTS. Core language concepts remain useful, while outdated setup instructions and browser-era Java are labeled or replaced. Java 26 is the current feature release; Java 25 is used here as the stable teaching baseline.
go to previous page   go to home page   go to next page

Answer:

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!"

Constructor Definition Syntax

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.

QUESTION 17:

Can a parameter be an object reference?

Can a parameter be a primitive data type?