How Can We Help?
What are Constructors in Java?
The constructor creates a new instance of the class. It initializes the necessary variables and performs all the work required to prepare the class for use. Let’s look at an example:
Syntax
Car c = new Car ();
Here, Car () is a constructor of the Car class. The constructor always has the same name as the corresponding class.
The constructor is made by writing a method with the same name as the class. That is why the constructor of the Car class is called Car().
Java Constructor Types
We have three types of constructors in Java which are :
- Default Constructor
- Constructor with Parameters (arguments).
- Constructor without Parameters (arguments).
1. Default Constructor
If we do not supply the class with any constructor, Java provides one generic, without arguments, the so-called no-args constructor; however, it is better to have your constructors.
Example
class Car {
string licensePlate; // e.g. "London BD5I SMR"
double speed; // km/h
double maxSpeed; // km/h
}
Note: Constructors have no return type. They return an instance of their class, but they do so implicitly, not explicitly.
2. Constructor with Parameters (Arguments)
We can also define a constructor that takes three arguments and uses them to initialize the corresponding variables:
Example 1
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;
}
The keyword ‘this’ is a reference object that refers to the current object.
Or we may want the initial speed to always be zero, and the maximum speed and license plate specified by the arguments:
Example 2
Car(String licensePlate, double maxSpeed) {
this.licensePlate = licensePlate;
this.speed = 0.0;
if (maxSpeed > 0) this.maxSpeed = maxSpeed;
else this.maxSpeed = 0.0;
}
3. Constructor without Parameters (Arguments)
We can define a constructor with no argument to support creating an object first from the class. Later on, the user would initialize the members of this constructor using setter methods or initialize some particular variables with specific values and change them afterward if need it.
Example
Car() {
this.licensePlate = "";
this.speed = 0.0;
this.maxSpeed = 140.0;
}
The method above is a constructor (with no arguments) that initializes the variable representing the license plate to an empty string, the speed to zero, and the maximum speed (maxSpeed) to 140.0 km / h.
Java Constructor Comprehensive Example
Let’s rewrite the Car class once again by incorporating all of the above constructors:
class Car {
string licensePlate; // e.g. "London BD5I SMR"
double speed; // km/h
double maxSpeed; // km/h
Car() {
this.licensePlate = "";
this.speed = 0.0;
this.maxSpeed = 140.0;
}
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;
}
Car(String licensePlate, double maxSpeed) {
this.licensePlate = licensePlate;
this.speed = 0.0;
if (maxSpeed > 0) this.maxSpeed = maxSpeed;
else this.maxSpeed = 0.0;
}
// getter (accessor) methods
String getLicensePlate() {
return this.licensePlate;
}
double getMaxSpeed() {
return this.maxSpeed;
}
double getSpeed() {
return this.speed;
}
// setter method for the attribute licensePlate
void setLicensePlate(String licensePlate) {
this.licensePlate = licensePlate;
}
// setter method for the attribute maxSpeed
void setMaximumSpeed(double maxSpeed) {
if (maxSpeed > 0) this.maxSpeed = maxSpeed;
else this.maxSpeed = 0.0;
}
}
}
As we can see above – the Car class has three constructors: first – with no arguments, second – with three arguments, and third – with two arguments.
The following program, CarTest, uses the third of these constructors (with two arguments) to initialize Car objects instead of setting values directly.
class CarTest{
public static void main(String args[]) {
Car c = new Car("London BD5I SMR", 130.5);
System.out.println(c.getLicensePlate() + " has speed of " + c.getSpeed() + " km per hour.");
}
}
Note: that we no longer have to worry about the licensePlate, speed, and maxSpeed attributes. All you need to know is how to construct a new copy of the Car class and print its data.
The question is whether the setLicensePlate () and setMaximumSpeed () methods are still needed when the licensePlate and maxSpeed attributes are set in the constructors. The answer depends on whether we want to allow them to be changed once the object has already been created. Classes that do not allow the attributes of their objects to change after they are created are called immutable. String is an example of such a class. You cannot change its data, and you can only create a new String object.
Constructors Overloading in Java
We can overload constructors if we have two or more constructors with the same name but with different arguments types or number of arguments.
Constructor Overloading in Java is a technique of having multiple constructors within the same class. Each constructor should take the same name but the differences in either the parameter lists or parameter types. The compiler differentiates between each one by looking for the number of parameters and their types.
Example
public class Oraask {
private int r;
private String str;
private Oraask(){ //default constructor
r=90;
}
private Oraask(string value){ // constructor with argument
str = value;
}
public static void main(String[] args) {
Oraask Obj1 = new Oraask();//default constructor
System.out.println("r = "+ Obj1.r);
Oraask Obj2 = new Oraask("Java"); // constructor with paramter
System.out.println("str = "+ Obj2.r);
}
}
Result |
r = 90 str = Java |
In this tutorial, you have learned What is a constructor in java? What are the different types of constructors? What is the use of constructors in java?.
If you have an inquiry or doubt, don’t hesitate to leave them in the comment section. We are waiting for your feedback.But remember to understand the concept very well, you need to practice more.
Hopefully, it was clear and concise.
Java Tutorials List:
- Java tutorials list: access all Java Tutorials.