๐ŸŽ‰ Special Offer !    Code: GET300OFF    Flat โ‚น300 OFF on every Java Course
Grab Deal ๐Ÿš€

Constructors in Java  


What is Constructor in Java ?
  • A constructor in Java is a special type of method used to initialize objects.
  • It is called when an instance of the class is created or say, when an object of a class is created.
  • Whenever an object is created using the new keyword, at least one constructor is called.
  • Syntax :
    access-modifiers ClassName(list of parameters)
    {
    	//body
    }
  • Example :
    public class Test
    {
        //constructor
        public Test()
        {
            //body
        }
        public static void main(String[] args)
        {
            Test t = new Test();    //constructor called automatically when we create object
        }
    }
  • Use of Constructor:
    • Constructors are used to initialize the object. It means that constructor assigns the values to the instance variables when an object is created. This can be done manually by the programmer or automatically by Java using a default constructor.

Rules for Constructors in Java
  • Below are rules for constructors in Java:
    1. The constructor must have the same name as that of class name.
    2. A constructor does not have a return type (not even void).
    3. Constructors can have any access modifier (public, private, protected or default) but cannot have non-access modifiers like static, final, abstract etc.
    4. The constructor is called automatically when an object is created.

Types of Constructors in Java
  • There are 3 types of constructors in Java:-
    1. Default Constructor (created by compiler)
    2. No-Args (No Argument) Constructor (created by programmer)
    3. Parameterized Constructor (created by programmer)
  • These are explained below one by one....

1. Default Constructor:
  • If programmer does'nt create any constructor, then Java compiler automatically creates one constructor which is known as default constructor.
  • It initializes an object properties with default values (0, null, false).
  • Syntax :
    class ClassName
    {
        // Default constructor is automatically provided by Java Compiler
    }
  • Example :
    public class Test
    {
        //here programmer didnt created any constructor, so Java compiler will create default constructor automatically.
        
        public static void main(String[] args)
        {
            Test t = new Test();    //default constructor called automatically when we create object
        }
    }
  • Some important points for Default Constructor:
    • The access modifier of Default Constructor is as that of class. If a class is public, the default constructor is public and so on.
    • Default Constructor has no parameters.
    • Default Constructor calls the superclass constructor (super()).
      public Test()
      {
          super();
      }

2. No-Args (No Argument) Constructor:
  • If a programmer creates the constructor without any parameters, then it is known as No Argument Constructor.
  • It is used to initialize objects with default values or perform some basic setup.
  • Syntax :
    class ClassName
    {
        // No-Argument Constructor
        ClassName()
        {
            // Initialization code (if needed)
        }
    }
  • Example :
    public class Student
    {
        String name;
    
        // No-Argument Constructor
        Student()
        {
            name = "Deepak";  // Assigning default value
        }
    
        void display()
        {
            System.out.println("Student Name: " + name);
        }
    
        public static void main(String[] args)
        {
            Student s1 = new Student(); // Calls no-argument constructor
            s1.display(); // Output: Student Name: Deepak
        }
    }

3. Parameterized Constructor:
  • If a programmer creates the constructor with parameters, then it is known as Parameterized Constructor.
  • It is used to:
    • Initialize objects with specific values instead of default values.
    • Avoid the need for setter methods after object creation.
    • Improve code readability by directly assigning values through the constructor.
  • Syntax :
    class ClassName
    {
        ClassName(dataType parameter1, dataType parameter2)
        {
            // Initialization code
        }
    }
  • Example :
    class Student
    {
        String name;
        int rollno;
    
        // Parameterized Constructor
        Student(String n, int rn)
        {
            name = n;
            rollno = rn;
        }
    
        void display()
        {
            System.out.println("Name: " + name + ", Roll No.: " + rollno);
        }
    
        public static void main(String[] args)
        {
            Student s1 = new Student("Deepak", 101); // Passing values
            s1.display();  // Output: Name: Deepak, Roll No.: 101
        }
    }