Java Reference
In-Depth Information
System.out.println(“*** big screen #1 ***”);
int channel = 4;
new BigScreenTV(channel);
short size = 53;
channel = 3;
String ratio = “16:9”;
System.out.println(“\n*** big screen #2 ***”);
new BigScreenTV(ratio, size, channel);
ratio = “5:4”;
size = 42;
channel = 4;
int volume = 7;
System.out.println(“\n*** big screen #3 ***”);
new BigScreenTV(ratio, size, channel, volume);
}
}
The Default Constructor
In Chapter 5, “Methods,” I discussed how the compiler generates a default constructor for
any class that does not explicitly declare a constructor. I mentioned that the default con-
structor does not contain any statements, but that is only partially true. Because the default
constructor is a constructor that does not invoke this() or super(), the compiler adds a call
to super() for you.
For example, suppose the BigScreenTV class looked similar to:
public class BigScreenTV extends Television
{
public String aspectRatio;
public short size;
}
The compiler would then generate and add the following constructor to this BigScreenTV
class:
public BigScreenTV()
{
super();
}
This BigScreenTV class will not compile for the Television class that did not include a no-
argument constructor. The BigScreenTV default constructor does not work in this situation.
By writing a class without a no-argument constructor, you are forcing all child classes to
explicitly add a constructor that contains a call to super(). For the most part, this is not a
major concern; however, this is another instance of why you should have a specific reason
to write a class that does not contain a no-argument constructor.
Search WWH ::




Custom Search