JAVA Constructors

A constructors in Java is similar  to a method  that is invoked  when object of the class is created . It can be used to set initial values for object attributes. A constructor has the same name as that of the class and does not have any return type.

There are three types of constructor.

  • Non-parametrised constructor.
  • Parametrised constructor.
  • Copy constructor.

Syntax:

class Text(){
  public Text(){
        //Constructor body
    }
}

Example of Non-Parametrised constructor:

class Main(){
    private String name;
    private int age;
    Student(){
        System.out.println("Constructor called");
    }
    public static void Main(String[]args){
        student s=new student();
        s.name="Learner";
        s.age="20";
        s.println();
        
    }
}

Example of Parametrised constructor:

class Student(){
    private String name;
    public void printInfo(){
        System.out.println(this.name);
        System.out.println(this.age);
    }
    Student(String name,String age){
        this.name=name;
        this.age=age;
    }
    public static void Main(String[]args){
        Student s=new Student("Learner",20);
        s.printInfo();
    }
}

Example of Copy Constructor:

class Student(){
    private String name;
    public void printInfo(){
        System.out.println(this.name);
        System.out.println(this.age);
    }
    Student(Student s2){
        this.name=s2.name;
        this.age=s2.age;
    }
    public class main{
    public static void Main(String[]args){
        Student s1=new Student();
        s1.name="Learner";
        s1.age=20;
        Student s2=new Student(s1);
        s2.printInfo();
    }
}