What is Constructor in JAVA || Types of Constructors || Why to use Constructors? Example of 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?
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());
}
}
Porsche911
Chaitanya
Harverd
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
Post a Comment