What is Constructors? Explain with an example?
A constructor forms a new instance of the class. It initializes all the variables and does any work essential to prepare the class to be used. In the line
Car c = new Car();
Car() is the constructor. A constructor has the similar name as the class.
If no constructor exists Java gives a generic one that takes no arguments (a noargs constructor), other than it's better to write your own. You make a constructor through writing a technique that has the same name as the class. Therefore the Car constructor is called Car().
Constructors do not have return types. They do return an instance of their own class, other than this is implicit, not explicit.
The subsequent method is a constructor that initializes license plate to an empty string, speed to zero, and maximum speed to 120.0.
Car() {
this.licensePlate = "";
this.speed = 0.0;
this.maxSpeed = 120.0;
}
Better yet, you can form a constructor which accepts three arguments and use those to initialize the fields as below.
Car(String licensePlate, double speed, double maxSpeed) {
this.licensePlate = licensePlate;
this.speed = speed;
if (maxSpeed > 0) this.maxSpeed = maxSpeed;
else this.maxSpeed = 0.0;
if (speed > this.maxSpeed) this.speed = this.maxSpeed;
if (speed < 0) this.speed = 0.0;
else this.speed = speed;
}
Or perhaps you always needs the initial speed to be zero, but needs the maximum speed and license plate to be specified:
Car(String licensePlate, double maxSpeed) {
this.licensePlate = licensePlate;
this.speed = 0.0;
if (maxSpeed > 0) this.maxSpeed = maxSpeed;
else this.maxSpeed = 0.0;
}