Skip to content

The constructor method

September 1, 2011

The constructor method is also known as the initialization method for the object being created.  Recall that objects have state or data associated with them.  Often, it is desirable to set the initial state or data of the object.

For example, when you create an object, like

Report summary = new Report; //where Report is a valid object

you are creating a instance of the Report class named summary.  Suppose the class looks like this:

public class Report{

public String reportName;

public String reportType;


When we create the summary object, we may wish to initialize the reportName and reportType fields. We accomplish this by defining a constructor method that is automatically executed when the object is created.  In Java the constructor method must follow the name of the class.  In this case, it would look like this:

public Report(){


We could initialize the fields by adding:

public Report(){

reportName = “some title”;

reportType = “some type”;


reportName would automatically get initialized to “some title” and reportType to “some type”.

We could update the fields dynamically, by adding parameters or aguments into the method header, like this:

public Report(String title, String type){

reportName =  title;

reportType = type;


Dynamic meaning we can pass data into the constructor method via the object creation statement, like this:

Report summary(“Fall 2011”, “summary”) = new Report;

When you create a Java object, think of it like this:

1                         2                                      3        4

Classname variable name = new Classname(optional parameters);

  1. Existing class name
  2. Instance variable name
  3. reserve word new
  4. call to object constructor method with optional parameters

From → Java

Leave a Comment

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: