A Constructor is a special kind of method. A constructor is invoked when a new object is created.
Every class has a constructor. If we do not explicitly write a constructor for a class the Java compiler builds a default constructor for that class.
Each time a new object is created, at least one constructor will be invoked.
Constructors are used to construct objects. The constructor has the same name as the defining class. Like regular methods, constructors can be overloaded ( A class can have more than one constructor), making it easy to construct objects with different initial data values.
To construct an object from a class, invoke a constructor of the class using the new operator.
Cars myCar = new Cars( "Iriz", 2016);
The following program uses three constructors.
Example-1:
// class Cars
public class Cars {
// instances
String make;
int year;
int speed;
// constructor-1
public Cars(String m, int y){
make = m;
year = y;
speed = 0;
}
// constructor-2
public Cars(String m){
make = m;
year = 2000;
speed = 0;
}
// constructor-3
public Cars(){
make = "";
year = 2000;
speed = 0;
}
// getter methods
public String getMake(){
return make;
}
public int getSpeed(){
return speed;
}
public int getYear(){
return year;
}
}
We can create multiple objects of one class.
Example-2:
public class TestCars {
public static void main(String[] args) {
Cars myCar = new Cars("Iriz", 2016);
Cars yourCar = new Cars("City");
System.out.println("myCar is " + myCar.getMake());
System.out.println("yourCar is " + yourCar.getMake());
}
}
In this program, objects myCar and yourCar are created from class Cars.
The output of this program will be:
myCar is Iriz
yourCar is City
We often see Java programs that have either static or public attributes and methods.
In the above example, we created a public method, which means that it can be accessed only by objects. Contrarily, the static method can be accessed without creating an object of the class.
Example-3
this program, PrintOutput is a static method. The PrintOutput method is used without creating an object.
public class TestCars2 {
public static void main(String[] args) {
Cars myCar = new Cars("Iriz", 2016);
Cars yourCar = new Cars("City");
PrintOutput(myCar.getMake(),yourCar.getMake());
}
public static void PrintOutput(String a, String b){
System.out.println("myCar is " + a);
System.out.println("yourCar is " + b);
}
}