Constructor in java and Use of this keyword in Java


A constructor is a special method that is called to create a new object.
PolicyHolder policyHolder = new PolicyHolder();
It is not mandatory for the coder to write a constructor for the class.It can be seen as a readily available, implicit method in every class.If a user defined constructor is available, it is called just after the memory is allocated for the object.If no user defined constructor is provided for a class, the implicit constructor initializes the member variables to its default values.
Example:
class Test{
int studentId;
public Test(int studentId){
this.studentId=studentId;
}
public int getId(){
return studentId;
}
}
public class Constructor{
public static void main(String args[]){
Test t=new Test(50);
System.out.println(t.studentId);
System.out.println(t.getId());
}
}
Result:
50
50
this Keyword in Java:
The methods in a class have a reference called this.“this” reference will refer to the object that has invoked the method.The this reference can be used in some cases to improve the readability of a program.
Example:
public class PolicyHolder{
private int policyNo;
private double bonus;
//Other Data Members
public void setPolicyNo(int policyNo)
{this.policyNo = policyNo;}
public int getPolicyNo(){return policyNo;}
public void setBonus(char bonus){this.bonus = bonus;}
public double getBonus(){return bonus;}
//Other Methods
}