A constructor in Java is a special method that is used to initialize objects.
- a constructor method name should be the same as the class name
- a constructor method can be method overloading.
- an object is created using the new() keyword, a constructor is called.
- It calls a default constructor if there is no constructor available in the class
sample/People.java
package sample;
public class People {
private String name;
private String country;
private String language;
public People(){
System.out.println("Empty Constructor is called");
}
public People(String name, String country, String language){
System.out.println("A Constructor with three parameters is called");
this.name = name;
this.country = country;
this.language = language;
}
public String getName(){
return this.name;
}
}
There are two constructors which are people an empty parameter constructor, and a constructor with three parameters. getName method will use to get the object’s name that will be set up by calling a constructor with three parameters.
sample/Main.java
package sample;
public class Main {
public static void main(String[] args) {
People tim = new People();
// Using the constructor method, initialize an object.
People mike = new People("Mike", "Spain", "Spanish");
System.out.println(mike.getName());
}
}
Empty Constructor is called
A Constructor with three parameters is called
Mike
- When a tim object is created, an empty constructor is called.
- When a mike object is created, a constructor with three parameters is called.
You can see with the method is called with printed messages. Also, with a constructor, you do not have to set a value individually. You will see a constructor extensively in Java because constructors are a very important part of creating objects from classes.