Java Reference
In-Depth Information
If you do add a constructor to your class, the compiler does not add the
default constructor to your class. Consider the Radio class shown in Listing 5.2.
public class Radio
{
public int volume;
public float tuning;
public char band;
public Radio(int v, char b)
{
volume = v;
band = b;
}
}
Listing 5.2 This Radio class declares a constructor and therefore does not have a default
no-argument constructor.
The Radio class shown in Listing 5.2 declares a constructor that has two
parameters: an int and a char. Because we added a constructor to this Radio
class, the compiler does not add another one for us.
Using Constructors
A constructor must be invoked when an object is instantiated using the new
keyword. A class can (and often does) have multiple constructors. You deter-
mine which constructor is invoked with the arguments used with the new
operator.
If a class has one constructor, there is only one way to instantiate an object of
that class type. For example, the Radio class shown in Listing 5.2 has only one
constructor. The signature of this constructor is the following:
public Radio(int v, char b)
Therefore, the only way to instantiate a Radio using the class shown in List-
ing 5.2 is to pass in an int and a char:
int volume = 7;
char band = 'A';
Radio radio = new Radio(volume, band);
The following statement does not compile with the Radio class shown in
Listing 5.2:
Radio radio = new Radio(); //invalid!
Search WWH ::




Custom Search