Java Reference
In-Depth Information
To avoid repeating code, you can have all the constructors invoke one con-
structor that does all the work. A constructor can use the
this
keyword to
invoke another constructor within the same class.
If a constructor uses the
this
keyword to invoke another constructor in
the class, the
this
statement must appear as the first line of code in the
constructor. (Otherwise, a compiler error will occur.)
The following Television class demonstrates using the
this
keyword to make
one constructor invoke another constructor. Notice that the
this
statement is
the first line of code in the constructor.
public class Television
{
public int channel;
public int volume;
public Television()
{
this(4, 10);
System.out.println(“Inside no-arg constructor”);
}
public Television(int c)
{
this(c, 10);
System.out.println(“Inside one-arg constructor”);
}
public Television(int c, int v)
{
System.out.println(“Inside two-arg constructor”);
channel = c;
volume = v;
}
}
The
this
keyword used within a constructor is not the same as the
this
reference that every object has to itself. The
this
keyword has two
different uses in Java.
The following ThisDemo program instantiates three Television objects by
using each of the three constructors in the Television class. Study the program
carefully and try to determine the output. The output is not obvious, so follow
the flow of control carefully. The actual output is shown in Figure 5.6.
public class ThisDemo
{
public static void main(String [] args)