Java Reference
In-Depth Information
A call to super() or this() must be the first line of code in every constructor.
If a constructor does not contain either, the compiler adds super() with
empty parentheses as the first line of code in the constructor. In the
BigScreenTV class, if the call to super() did not appear, the compiler would
have added it for us.
In the Television class, the constructor with two int parameters does not
call super() or this(), so the compiler adds super() as the first line of code,
thereby invoking the no-argument constructor in the Object class.
The following ConstructorDemo program instantiates a BigScreenTV object.
Follow the flow of control carefully and try to determine the output, which is
shown in Figure 6.5.
public class ConstructorDemo
{
public static void main(String [] args)
{
System.out.println(“Constructing a big screen TV”);
BigScreenTV tv = new BigScreenTV();
System.out.println(“Done constructing TV”);
}
}
Within main() of ConstructorDemo, we instantiate a BigScreenTV object:
BigScreenTV tv = new BigScreenTV();
This statement invokes the no-argument constructor in the BigScreenTV
class. The constructor in BigScreenTV invokes the no-argument constructor in
Television. The no-argument Television constructor invokes the other Televi-
sion constructor, which does not have a this() or super() statement. Therefore,
the compiler added super(), causing the no-argument constructor in Object to
be invoked.
When the Object constructor is finished, control returns to the Television
constructor with two arguments, which executes and outputs:
Inside Television(int, int)
Figure 6.5
The output of the ConstructorDemo program.
Search WWH ::




Custom Search