In this tutorial, we will learn about the Constructors in Java, or its types, and how to use them with the help of examples.

Define Constructors in Java

  • It is a member function of class.
  • Its name same as class name .
  • The constructor calls automatically whenever we create object of the class each time.
  • The constructor can be parameterize but no return type even void.
  • The use of constructor is it can be use to initialize the data value of data member of the class as well as it can be use to open file or database that can be use with object.
  • In a class we can define more than one constructor and this will be called constructor overloading.(function overloading).
  • Constructor always be define with public scope.

Syntax

class ClassName {
   ClassName() {
   }
}
Syntax of Constructors

Types of Constructor

  • Default constructor
  • Parameterized constructor
Types of Constructor in Java
Types of Constructor in Java

Default constructor in Java

A constructor that has no parameter is know as Default constructor in Java. This constructor provides the default values to the object depending on the type.

Example of Default constructor in Java

Input Value

public class consv {
    public consv(){
    System.out.println("no constuctor");
}
public static void main(String[] args){
    consv d = new consv();
}
}
Default constructor in Java

Let’s run the code

Input Value

Output Value

Output Value

Parameterized Constructor

A constructor that has parameter is know as Parameterized constructor in Java.

Example Of Parameterized Constructor

Input Value

public class consv {
    private String name;
    public consv(String n) {
        System.out.println("parameterized Construction");
        this.name = n;
    }
    public String getName(){
        return name;
    }
public static void main(String[] args){
    consv d = new consv("Basic engineer");
    System.out.println(d.getName());
}
}
Parameterized Constructor

Let’s run the code

Input Value

Output Value

Output Value

If you have any queries regarding this article or if I have missed something on this topic, please feel free to add in the comment down below for the audience. See you guys in another article.

To know more about JAVA Wikipedia please click here .

Stay Connected Stay Safe, Thank you


Basic Engineer

Hey Readers! We have more than fifteen years of experience in Software Development, IoT, Telecom, Banking, Finance and Embedded domain. Currently we are actively working on Data Science, ML and AI with multiple market leaders worldwide. Happy Reading. Cheers!

0 Comments

Leave a Reply

Avatar placeholder

Your email address will not be published. Required fields are marked *