DEV Community

S Sarumathi
S Sarumathi

Posted on

Constructor In Java

Constructor:
A constructor in Java is a special member that is called when an object is created. It initializes the new object’s state. It is used to set default or user-defined values for the object's attributes

  • A constructor has the same name as the class.

  • It does not have a return type, not even void.

  • It can accept parameters to initialize object properties

Types Of Constructor:

1. Parameterized Constructor:
A parameterized constructor takes values(parameters) to initialize the object

class Student {
    String name;
    int age;

    Student(String str,int i) {
      name = str;
      age = i;
    }

    public static void main(String[] args) {
        Student s1 = new Student("Ganga",21);
        s1.display();
    }
       void display() {
        System.out.println("Name: " + name);
         System.out.println("age: " + age);
    }
}
Enter fullscreen mode Exit fullscreen mode

Output:

2.Default Constructor:

A default constructor is a constructor with no parameters
Enter fullscreen mode Exit fullscreen mode

class Student

public class Student{
   String name;
    int age;

    Student() {
        System.out.println("Default constructor");
    }

    public static void main(String[] args) {
        Student s1 = new Student();
        s1.name="Ganga";
        s1.age=21;
        s1.display();
    }

    void display() {
        System.out.println("Name: " + name);
        System.out.println("Age: " + age);
    }
}
Enter fullscreen mode Exit fullscreen mode

Output:

3.Constructor Overloading:

Constructor overloading means having multiple constructors in the same class with different parameters lists

public class Student{
   String name;
    int age;


 public  Student(String Name,int i) {
       name=Name;
       age=i;
    }
public Student(){
       System.out.println("Constructor");
}
    public static void main(String[] args) {
        Student s1 = new Student("Ganga",21);

        System.out.println(s1.name);
        System.out.println(s1.age);
        Student s2=new Student();
    }        

}
Enter fullscreen mode Exit fullscreen mode

Output:

Top comments (0)