Constructors
| |||
A constructor creates a new instance of the class. It initializes all the variables and does any work necessary to prepare the class to be used. In the line
Car() is the constructor. A constructor has
the same name as the class.
If no constructor exists Java provides a generic one
that takes no arguments (a noargs constructor), but it's better
to write your own. You make a constructor by writing a method that has the
same name as the class. Thus the Car constructor is called Constructors do not have return types. They do return an instance of their own class, but this is implicit, not explicit. The following method is a constructor that initializes license plate to an empty string, speed to zero, and maximum speed to 120.0.
Better yet, you can create a constructor that accepts three
arguments and use those to initialize the fields as below.
Or perhaps you always want the initial speed to be zero,
but require the maximum speed and license plate to be specified:
| |||
|