Java Reference
In-Depth Information
{
System.out.println(“Instantiating first television”);
Television t1 = new Television();
System.out.println(t1.volume + “ “ + t1.channel);
int channel = 206;
System.out.println(“Instantiating second television”);
Television t2 = new Television(channel);
System.out.println(t2.volume + “ “ + t2.channel);
int volume = 7;
System.out.println(“Instantiating third television”);
Television t3 = new Television(channel, volume);
System.out.println(t3.volume + “ “ + t3.channel);
}
}
The first statement within main() outputs the following:
Instantiating first television
Then, a Television object is instantiated using no arguments. Flow of control
jumps to the no-argument constructor of the Television class. The first statement
in the following constructor causes flow of control to jump to the two-argument
constructor in the Television class:
this(4,10);
The two-argument constructor executes, then control jumps back to the one-
argument constructor, which executes. Therefore, the output is as follows:
Inside two-arg constructor
Inside no-arg constructor
Notice that the default constructor creates a Television object with an initial
volume of 10 and channel 4. The second Television object in ThisDemo uses
the one-argument constructor, which uses the this keyword to invoke the two-
argument constructor, creating the following output:
Inside two-arg constructor
Inside one-arg constructor
The third Television object invokes the two-argument constructor directly,
creating the following output:
Inside two-arg constructor
The entire output is shown in Figure 5.6.
Search WWH ::




Custom Search