What is Constructor in JAVA || Types of Constructors || Why to use Constructors? Example of Constructor

Constructor

 


What is Constructor?

  • Constructor is one of the key element in object oriented programming. With the help of constructors we can initialize objects while making it.
  • If we don't create any constructor JAVA will create its own constructor.  

Types of Constructors

  • Default Constructor - This is crated by JAVA when we create an object
  • Parameterized Constructor - We create this constructor to initialize the object while creating it 

Why we use Constructors in Framework?

In POM (Page Object Model) Structure of Framework we create constructor of Locators file to travers the driver from Locators to Action and action to Test.

Example of Constructor: Code

public class ConstructorImplimentation {

private String MyName;

private String MySchoolName;

private String MyCar;

public ConstructorImplimentation (String MyName, String MySchoolName, String MyCar) {

this.MyCar=MyCar;

this.MyName=MyName;

this.MySchoolName=MySchoolName;

}

public String getMyName() {

return MyName;

}

public void setMyName(String myName) {

MyName = myName;

}

public String getMySchoolName() {

return MySchoolName;

}

public void setMySchoolName(String mySchoolName) {

MySchoolName = mySchoolName;

}

public String getMyCar() {

return MyCar;

}

public void setMyCar(String myCar) {

MyCar = myCar;

}

}

class Studentinfo{

public static void main(String[] args) {

ConstructorImplimentation c = new ConstructorImplimentation("Chaitanya", "Harverd", "Porsche911");

System.out.println(c.getMyCar());

System.out.println(c.getMyName());

System.out.println(c.getMySchoolName());

}

}

OutPut

Porsche911

Chaitanya

Harverd


Constructor Chaining

Using constructor within constructor is call Constructor Chaining. 

Example of Constructor Chaining: Code


public class ConstructorImplimentation {

private String MyName;

private String MySchoolName;

private String MyCar;

public ConstructorImplimentation(String MyName, String MySchoolName) {

this(MyName, MySchoolName, "Ferrari");

}

public ConstructorImplimentation (String MyName, String MySchoolName, String MyCar) {

this.MyCar=MyCar;

this.MyName=MyName;

this.MySchoolName=MySchoolName;

}

public String getMyName() {

return MyName;

}

public void setMyName(String myName) {

MyName = myName;

}

public String getMySchoolName() {

return MySchoolName;

}

public void setMySchoolName(String mySchoolName) {

MySchoolName = mySchoolName;

}

public String getMyCar() {

return MyCar;

}

public void setMyCar(String myCar) {

MyCar = myCar;

}

}

class Studentinfo{

public static void main(String[] args) {

ConstructorImplimentation c = new ConstructorImplimentation("Abhi", "Cambridge");

System.out.println(c.getMyCar());

System.out.println(c.getMySchoolName());

}

}


Comments