Introduction

In Java, a constructor initializes its object. It seems similar to a method in Java but is completely different.

Constructor in Java

Constructors are very important in Java. They are used to initialize the object in Java. They are invoked at the time of the creation of the object. Constructors are used to providing the values for the object.

Main Purpose of Constructor

Creation of the instance of a class is the sole purpose of a constructor in Java.

Rules for the Constructor

Invocation of Constructor

Constructors are invoked when the instance of the class is created.
Example
  1. package demo;
  2. public class Demo {
  3. public Demo() {
  4. System.out.println("Constructor");
  5. }
  6. public static void main(String[] args) {
  7. Demo cr = new Demo();
  8. }
  9. }
Output
constructor invocation

Types of Constructors

In Java, constructors are of two types.
Default Constructor: A default constructor is a constructor that has no parameters.
Example
  1. package demo;
  2. public class Demo {
  3. public Demo() {
  4. System.out.println("Demo constructor is created");
  5. }
  6. public static void main(String[] args) {
  7. Demo d = new Demo();
  8. }
  9. }
Output
default constructor
Parameterized Constructor: A parameterized constructor is a constructor that has parameters.
Example
  1. package demo;
  2. public class Demo {
  3. int rollno;
  4. String name;
  5. String standard;
  6. Demo(int r, String n, String s) {
  7. rollno = r;
  8. name = n;
  9. standard = s;
  10. }
  11. void show() {
  12. System.out.println("rollno- " + rollno + " " + "name- " + name + " " + "standard- " + standard);
  13. }
  14. public static void main(String[] args) {
  15. Demo d = new Demo(11, "sam", "fifth");
  16. d.show();
  17. }
  18. }
Output
parameterized constructor

Constructor Overloading

We can overload constructors but cannot override them. We can create multiple constructors in a class.
Example
  1. package demo;
  2. public class Demo {
  3. int rollno;
  4. String name;
  5. String standard;
  6. Demo(int r, String n, String s) {
  7. rollno = r;
  8. name = n;
  9. standard = s;
  10. }
  11. Demo(int r, String n) {
  12. rollno = r;
  13. name = n;
  14. }
  15. void show() {
  16. System.out.println("rollno- " + rollno + " " + "name- " + name + " " + "standard- " + standard);
  17. }
  18. public static void main(String[] args) {
  19. Demo d1 = new Demo(11, "sam", "fifth");
  20. Demo d2 = new Demo(12, "ram");
  21. d1.show();
  22. d2.show();
  23. }
  24. }
Output
constructor overloading
Difference Between Constructor and Method

Summary

This article explains constructors in Java and also the difference between constructors and methods in Java.