Initializing Data              
                                         
Recall that creating an object is called instantiation. You instantiate an object using the “new” keyword. Some
object types allow information to be given during instantiation. This allows instance variables of the object to
be set (initialized) when the object is created. This is opposed to modifying them after the object is created.
Revisiting the previous point example, the (2,5) point in space can be created in one line of code.


Point myPoint = new Point(2, 5);


When you create an object with the “new” keyword, you are actually calling a special method called a
constructor.

Below is what the Point’s constructor method may look like.


public Point(int param1, int param2) {
 x = param1;
 y = param2;
}


The constructor is responsible for initialization of an object when it is instantiated. Constructor methods can
only be called during instantiation. All objects have at least one constructor but can have as many as they
want or need. The benefit of multiple constructors is flexibility. Depending on what information you have
when you create on object, you may have the ability to pass in all, some, or no data.

For example, imagine customers can submit information on some website about themselves. Say your
application must create an object to represent that customer. Customers may submit all information (name,
address, phone, email, and so on) about themselves.


Customer c = new Customer(“Jim”, “Hugo”, “999-9999”, “jwhite@i.com”);


Some might only submit their email address.


Customer c = new Customer(“jwhite@i.com”);


Still others might enter their name and address but no phone or email.


Customer c = new Customer(“Jim”, “Hugo”);


Customer here has three different constructors based on what instance variables need to be initialized. You’ll
see more information on constructors in the next section.
Initializing Data
Table of Contents
Copyright (c) 2008.  Intertech, Inc. All Rights Reserved.  This information is to be used exclusively as an
online learning aid.  Any attempts to copy, reproduce, or use for training is strictly prohibited.
Courseware
Training Resources
Tutorials
Services