Java Reference
In-Depth Information
Control then returns to the no-argument Television constructor, which exe-
cutes and outputs:
Inside Television()
Control then returns to the BigScreenTV constructor, which executes last
and outputs:
Inside BigScreenTV()
After all three constructors are done, the object is instantiated and the new
operator returns a reference to the new BigScreenTV object. The entire output
of the ConstructorDemo program is shown in Figure 6.5.
Invoking a Parent Class Constructor
The super keyword is used to invoke a parent class constructor. The compiler
adds super() with empty parentheses if a constructor does not explicitly use the
super keyword, causing the parent's no-argument constructor to be invoked.
What happens, however, if the parent class does not have a no-argument
constructor? Calling super() with empty parentheses does not compile, and
the child class constructors need to explicitly invoke a parent constructor,
passing in the appropriate arguments to the parent class constructors.
For example, suppose we modify the Television class as follows so that it no
longer has a no-argument constructor.
public class Television
{
public int channel, volume;
public Television(int c)
{
this(c,5);
System.out.println(“Inside Television(int)”);
}
public Television(int c, int v)
{
System.out.println(“Inside Television(int, int)”);
channel = c;
volume = v;
}
}
Figure 6.6 shows what happens when the BigScreenTV class is compiled
using this new Television class.
Search WWH ::




Custom Search