|
The Java Language
|
CS 161 - Java |
Constructors are the mechanism by which new instances of a
class are created from the blueprint of the class definition.
-
Constructors look something like method definitions except
- They always have the same name as the class
- They never return any type of value
-
You "call" a constructor using the new operator and
supplying any needed constructor arguments.
-
Every class has, by default, a constructor:
public ClassName() {
}
that takes no arguments and does no special initialization.
-
If you don't define one, Java will create a default, no-arg constructor.
-
If you define any constructor, with or without arguments, Java assumes you
know what you are doing and defines no default constructor.
-
Recommendation:
If you define any constructors that take arguments,
always define a "no argument" constructor too.
Question: Why would you want to define a constructor?