Constructor in java is one kind of special method that is being called when an object of a class is created. In java, all classes have default constructor. If you don't create any constructor externally, then java creates one for you.
What is the use of constructor?
Constructor is created and used for initializing the data members of a class at the time of object creation.
Syntax:
Note: Constructor name must be the same as class name but without return types. Constructor can not have return types like int, void etc. constructor can be public or private. The only difference between public and private constructor is that, if your constructor is private then you can only create instances (objects) within the declared class.
If you have a class A then the name of constructor would be A(){}
Like:
public class A {
//data members
//constructor
public A (){
//initialize data members
}
}
Remember, constructor is called at the time of object creation of a class.
Look at the example below:
public class A {
//data members
int number; //declare a variable
//constructor
public A (){
//access the A class member
number = 10; //initialize the variable number
}
public static void main (String[] args) {
//create an object of class A
A obj = new A();
System.out.println(obj.number);
}
}
/**
* Output:
* 10
*/
But the real use of constructor is to, initialize the class data members. And invoke at the time of creating objects.
Example:
public class Person{
public String firstName;
public String lastName;
public Person(String firstName, String lastName){
this.firstName = firstName;
this.lastName = lastName;
//this keyword is used to refer the current object (person properties )
}
public static void main (String[] args) {
//creating object of class Person
Person person = new Person("Mark", "Smith"); //initialize the data members
System.out.println("FullName: " person.firstName +" "+person.lastName);
}
}
/**
* Output:
* FullName: Mark Smith
*/
You can see that, we have passsd the data values of Person class members at the time of creating object and then access the values of Person class.
Note: If your constructor contains parameters, then you must pass the parameter values at time of creating objects. Like the above Person class example.
# Using this keyword
We already discussed that, this keyword refers the current object of a class. What if we don't use this keyword to initialize the class data members? Then, the parameters of constructor be must different than the data members of a class. Like:
public class A {
int x;
public A (int y){
x = y ;
}
//main method
}
But if you use this keyword then, class members name and parameters name should be same.
public class A {
int x;
public A (int x){
this.x = y ;
}
//main method
}