Java Reference
In-Depth Information
Remember that when an object is instantiated using the new keyword, the
memory is allocated and zeroed out. Therefore, the initial values of the fields
of an object are zero values (see Table 4.1). Without a constructor, you have to
go in and initialize all the fields so that the object has meaningful data. A con-
structor provides an opportunity to construct the object so that its fields have
meaningful data while the object is being instantiated.
What makes a constructor different from a method is that a constructor sat-
isfies the following two properties:
The name of the constructor must match the name of the class.
■■
A constructor does not declare a return value, not even void.
■■
For example, if we want to add a constructor to the Radio class discussed ear-
lier, the name of the constructor has to be Radio and no return value is declared.
Listing 5.1 shows the Radio class with two constructors added.
public class Radio
{
public int volume; //0-10
public float tuning; //Current station tuned in
public char band; //'A' for AM or 'F' for FM
public Radio()
{
System.out.println(“Inside no-argument constructor”);
tuning = 80.0F;
band = 'F';
volume = 5;
}
public Radio(float t)
{
System.out.println(“Inside float constructor”);
tuning = t;
band = 'A';
volume = 8;
}
//The remainder of the class definition...
}
Listing 5.1
This Radio class has two constructors.
When adding multiple constructors to a class, the rules of method
overloading apply. Each constructor must have a unique parameter
list that makes it distinguishable from the other constructors.
Search WWH ::




Custom Search