Java Reference
In-Depth Information
The previous statement attempts to invoke a no-argument constructor, but the
Radio class shown in Listing 5.2 does not declare a no-argument constructor.
A Class with Multiple Constructors
If a class has multiple constructors, the new operator can be used for each con-
structor in the class. For example, the Radio class shown in Listing 5.1 has two
constructors. Their signatures are as follows:
public Radio()
public Radio(float t)
This gives us two ways to instantiate a new Radio. To invoke the no-argument
constructor, use the new operator with no arguments:
Radio x = new Radio();
To invoke the constructor that has a float parameter, pass in a float with the
new operator:
float station = 100.3F;
Radio y = new Radio(station);
Study the following ConstructorDemo program and try to determine the
output. (Note that the ConstructorDemo program is using the Radio class
defined in Listing 5.2.) The program output is shown in Figure 5.5.
public class ConstructorDemo
{
public static void main(String [] args)
{
System.out.println(“Instantiating the first Radio”);
Radio x = new Radio();
System.out.println(“Instantiating the second Radio”);
float station = 100.3F;
Radio y = new Radio(station);
System.out.println(x.volume + “ “ + x.tuning
+ “ “ + x.band);
System.out.println(y.volume + “ “ + y.tuning
+ “ “ + y.band);
}
}
Search WWH ::




Custom Search