info@tutsfinder.in



Java Constructor

Constructors are special functions that are used to initialize the member of any class.

A pseudo-method that creates an object. In the Java programming language, constructors are instance methods with the same name as their class.

Constructors are invoked using the new keyword.

It is called when the instance of the class is created.

Rules-
• Class name must be same as constructor name.
• There is not any explicit return type.



Defining a Constructor in Java

A simple Java constructor declaration example. In which a class with single constructor -

public class TutsFinder {

       public TutsFinder() {

       }

}


Types of Constructors-


Default constructor - When constructor does not have any parameter then it is called as default parameter.

Example to define Default Constructor -

class Tuts {
     public Tuts()
     {
         System.out.println("Java Tutorials");
    }
     public static void main (String[] args)
    {
         Tuts obj = new Tuts();
    }
}


Output:

Java Tutorials


Parameterized constructor - A constructor with arguments is known as parameterized constructor.


Example to define Parameterized Constructor -

import java.io.*;
class Tuts

    {
    String name;
    int id;

    Tuts(String name, int id)
    {
        this.name = name;
         this.id = id;
    }


    public static void main (String[] args)     {
        Tuts obj = new Tuts("Java Tutorials", 1);
        System.out.println("Tutorials Name :" + obj.name + " and Tutorials Id :" + obj.id);
    }
}



Output:

Tutorials Name: Java Tutorials and Tutorials Id: 1