Java Reference
In-Depth Information
Default Constructor
If you write a class and do not add a constructor, the compiler generates a
default constructor in your class. This default constructor is public, has no
parameters, and does not do anything.
For example, if the Radio class does not declare a constructor, the compiler
adds the following:
public Radio()
{}
Notice that this follows the rules of a constructor: The constructor name
matches the class name, and there is no return value. Also notice that the con-
structor contains no statements.
A Class with No Default Constructor
If you do not add a constructor to a class, the compiler generates a default constructor for
the class. This default constructor does not contain any parameters. If you add one or more
constructors to your class, no matter what their parameter lists are, the compiler does not
add a default constructor to your class.
The following class does not have a default constructor:
public class Television
{
public int channel;
public Television(int c)
{
channel = c;
}
}
Because there is only one constructor in this Television class, the only way to instantiate
a new Television object is to pass in an int:
Television t1 = new Television(4);
The point I want to make with this example is that the following statement does not
compile:
Television t2 = new Television();
This statement is attempting to invoke a no-argument constructor, but the Television
class does not contain a no-argument constructor, thereby causing a compiler error. It is not
uncommon to write a class without a no-argument constructor, as demonstrated by many
classes in the Java API.
Search WWH ::




Custom Search