Sitemap
Towards Dev

A publication for sharing projects, ideas, codes, and new theories.

Constructor in Java

--

In Java, a constructor is a block of code that is used to create an instance of a class. At the time of calling the constructor, memory was allocated for the Java object.

We can find mainly three rules while creating the constructor of a class.

01. The contractor’s name must be the same as its class name.

02. A constructor must not have an explicit return type.

03. A constructor cannot be final, static, abstract, or synchronized.

There are mainly two types of constructors available in Java.

Get Sachith Ariyathilaka’s stories in your inbox

Join Medium for free to get updates from this writer.

01. No-Arg Constructor (Default Constructor): This type of constructor does not have any parameters. Mainly, this type of constructor holds the default values of a class. Following are example code blocks for the default constructor.

/**
* The main class.
*
* @author Sachith Ariyathilaka
* @version 1.0.0
* @since 2024/12/15
**/
public class Test {
private String name;
private int age;

public Test() {
this.name = "Sachith Ariyathilaka";
this.age = 26;
}

public static void main(String args[]) {
Test test = new Test();
System.out.println("Name: " + test.name); // Name: Sachith Ariyathilaka
System.out.println("Age: " + test.age); // Age: 26
}
}

As per the above example, we will create the constructor by using the new keyword.

02. Parameterized Constructor: A constructor that has at least one parameter is called a parameterized constructor. This constructor is used to pass values to the Java object while creating it. Following are example code blocks for the parametrized constructor.

/**
* The main class.
*
* @author Sachith Ariyathilaka
* @version 1.0.0
* @since 2024/12/15
**/
public class Test {
private final String name;
private final int age;

public Test(String name, int age) {
this.name = name;
this.age = age;
}

public static void main(String args[]) {
Test test = new Test("Sachith Ariyathilaka", 26);
System.out.println("Name: " + test.name); // Name: Sachith Ariyathilaka
System.out.println("Age: " + test.age); // Age: 26
}
}

Now let’s discuss some of the main differences between the Java constructors and methods.

01. A constructor must not have any return type, and a method must have a return type.

02. Java compilers created the default constructor while we are not included in a class. But methods do not create automatically while methods are not implemented.

03. The constructors must name it as the class name. While method names should not be the same as the class name.

--

--

Towards Dev
Towards Dev

Published in Towards Dev

A publication for sharing projects, ideas, codes, and new theories.