Java Constructor Tutorial: Learn Basics and Best Practices

Feb 12, 2025 07:00 AM - 1 month ago 49353

Introduction

Constructor successful java is utilized to create the lawsuit of the class. Constructors are almost akin to methods isolated from for 2 things - its sanction is the aforesaid arsenic the people sanction and it has nary return type. Sometimes constructors are besides referred to arsenic typical methods to initialize an object.

Constructor successful Java

Whenever we usage caller keyword to create an lawsuit of a class, the constructor is invoked and the entity of the people is returned. Since constructor tin only return the entity to class, it’s implicitly done by java runtime and we are not expected to adhd a return type to it. If we adhd a return type to a constructor, past it will go a method of the class. This is the measurement java runtime separate betwixt a normal method and a constructor. Let’s presume we person pursuing codification successful Employee class.

public Employee() { System.out.println("Employee Constructor"); } public Employee Employee() { System.out.println("Employee Method"); return new Employee(); }

Here the first 1 is simply a constructor, announcement that location is nary return type and nary return statement. The 2nd 1 is simply a normal method wherever we are again calling the first constructor to get Employee lawsuit and return it. It’s recommended to not person method sanction aforesaid arsenic the people sanction because it creates confusion.

Types of Constructor successful Java

There are 3 types of constructor successful java.

  1. Default Constructor
  2. No-Args constructor
  3. Parameterized constructor

Let’s look into each these constructor types pinch illustration programs.

Default Constructor successful Java

It’s not required to ever supply a constructor implementation successful the people code. If we don’t supply a constructor, past java provides default constructor implementation for america to use. Let’s look astatine a elemental programme wherever default constructor is being utilized since we will not explicitly specify a constructor.

package com.journaldev.constructor; public class Data { public static void main(String[] args) { Data d = new Data(); } }
  1. Default constructor only domiciled is to initialize the entity and return it to the calling code.
  2. Default constructor is ever without statement and provided by java compiler only erstwhile location is nary existing constructor defined.
  3. Most of the clip we are good pinch default constructor itself arsenic different properties tin beryllium accessed and initialized done getter setter methods.

No-Args Constructor

Constructor without immoderate statement is called a no-args constructor. It’s for illustration overriding the default constructor and utilized to do immoderate pre-initialization worldly specified arsenic checking resources, web connections, logging, etc. Let’s person a speedy look astatine the no-args constructor successful java.

package com.journaldev.constructor; public class Data { public Data() { System.out.println("No-Args Constructor"); } public static void main(String[] args) { Data d = new Data(); } }

Now erstwhile we will telephone caller Data(), past our no-args constructor will beryllium called. Below image illustrates this behavior, cheque the console output of the program. no args constructor successful java

Parameterized Constructor

Constructor pinch arguments is called parameterized constructor. Let’s look astatine the illustration of parameterized constructor successful java.

package com.journaldev.constructor; public class Data { private String name; public Data(String n) { System.out.println("Parameterized Constructor"); this.name = n; } public String getName() { return name; } public static void main(String[] args) { Data d = new Data("Java"); System.out.println(d.getName()); } }

java people constructor pinch parameters

Constructor Overloading successful Java

When we person much than 1 constructors, past it’s constructor overloading successful java. Let’s look astatine an illustration of constructor overloading successful java program.

package com.journaldev.constructor; public class Data { private String name; private int id; public Data() { this.name = "Default Name"; } public Data(String n) { this.name = n; } public Data(String n, int i) { this.name = n; this.id = i; } public String getName() { return name; } public int getId() { return id; } @Override public String toString() { return "ID="+id+", Name="+name; } public static void main(String[] args) { Data d = new Data(); System.out.println(d); d = new Data("Java"); System.out.println(d); d = new Data("Pankaj", 25); System.out.println(d); } }

Private Constructor successful Java

Note that we can’t usage abstract, final, static and synchronized keywords pinch constructors. However we tin usage entree modifiers to power the instantiation of people object. Using nationalist and default entree is still fine, but what is the usage of making a constructor private? In that lawsuit immoderate different people won’t beryllium capable to create the lawsuit of the class. Well, a constructor is made backstage successful lawsuit we want to instrumentality singleton creation pattern. Since java automatically provides default constructor, we person to explicitly create a constructor and support it private. Client classes are provided pinch a inferior fixed method to get the lawsuit of the class. An illustration of backstage constructor for Data people is fixed below.

private Data() { }

Constructor Chaining successful Java

When a constructor calls different constructor of the aforesaid class, it’s called constructor chaining. We person to usage this keyword to telephone different constructor of the class. Sometimes it’s utilized to group immoderate default values of the people variables. Note that different constructor telephone should beryllium the first connection successful the codification block. Also, location should not beryllium recursive calls that will create an infinite loop. Let’s spot an illustration of constructor chaining successful java program.

package com.journaldev.constructor; public class Employee { private int id; private String name; public Employee() { this("John Doe", 999); System.out.println("Default Employee Created"); } public Employee(int i) { this("John Doe", i); System.out.println("Employee Created pinch Default Name"); } public Employee(String s, int i) { this.id = i; this.name = s; System.out.println("Employee Created"); } public static void main(String[] args) { Employee emp = new Employee(); System.out.println(emp); Employee emp1 = new Employee(10); System.out.println(emp1); Employee emp2 = new Employee("Pankaj", 20); System.out.println(emp2); } @Override public String toString() { return "ID = "+id+", Name = "+name; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } }

I person overridden the toString() method to people immoderate useful accusation astir Employee object. Below is the output produced by supra program.

Employee Created Default Employee Created ID = 999, Name = John Doe Employee Created Employee Created with Default Name ID = 10, Name = John Doe Employee Created ID = 20, Name = Pankaj

Notice really 1 constructor is being called from different constructor, that’s called constructor chaining process.

Java Super Constructor

Sometimes a people is inherited from a superclass, successful that case, if we person to telephone superclass constructor past we tin do it utilizing ace keyword. Let’s person a look astatine an illustration of utilizing ace people constructor. Note that ace constructor telephone should beryllium the first connection successful the kid people constructor. Also erstwhile instantiating kid people constructor, java first initializes the ace people and past kid class. So if the ace people constructor is not explicitly called past default aliases no-args constructor is called by java runtime. Let’s understand these concepts done immoderate illustration program. Let’s presume we person 2 classes for illustration below.

package com.journaldev.constructor; public class Person { private int age; public Person() { System.out.println("Person Created"); } public Person(int i) { this.age = i; System.out.println("Person Created pinch Age = " + i); } } package com.journaldev.constructor; public class Student extends Person { private String name; public Student() { System.out.println("Student Created"); } public Student(int i, String n) { super(i); this.name = n; System.out.println("Student Created pinch sanction = " + n); } }

Now if we create a Student entity for illustration below;

Student st = new Student();

What will beryllium the output produced? The output of the supra codification will be:

Person Created Student Created

So the telephone went to the no-args constructor of Student people since location was nary ace telephone successful the first connection the no-args aliases default constructor of Person people is called. Hence the output. What if we are utilizing parameterized constructor of Student people arsenic Student st = caller Student(34, "Pankaj");, the output will be:

Person Created with Age = 34 Student Created with name = Pankaj

Here the output is clear because we are explicitly calling superclass constructor, truthful Java doesn’t request to do immoderate other activity from their side.

Java Copy Constructor

Java transcript constructor takes the entity of the aforesaid people arsenic an statement and creates a transcript of it. Sometimes we request a transcript of different entity to do immoderate processing. We tin do this by pursuing ways:

  1. implement cloning
  2. providing a inferior method for deep copy of the object.
  3. Having a transcript constructor

Now let’s spot really to constitute a transcript constructor. Suppose we person a people Fruits for illustration below.

package com.journaldev.constructor; import java.util.ArrayList; import java.util.List; public class Fruits { private List<String> fruitsList; public List<String> getFruitsList() { return fruitsList; } public void setFruitsList(List<String> fruitsList) { this.fruitsList = fruitsList; } public Fruits(List<String> fl) { this.fruitsList = fl; } public Fruits(Fruits fr) { List<String> fl = new ArrayList<>(); for (String f : fr.getFruitsList()) { fl.add(f); } this.fruitsList = fl; } }

Notice that Fruits(Fruits fr) is performing a heavy transcript to return the transcript of the object. Let’s look astatine a trial programme to understand why it’s amended to person transcript constructor to transcript an object.

package com.journaldev.constructor; import java.util.ArrayList; import java.util.List; public class CopyConstructorTest { public static void main(String[] args) { List<String> fl = new ArrayList<>(); fl.add("Mango"); fl.add("Orange"); Fruits fr = new Fruits(fl); System.out.println(fr.getFruitsList()); Fruits frCopy = fr; frCopy.getFruitsList().add("Apple"); System.out.println(fr.getFruitsList()); frCopy = new Fruits(fr); frCopy.getFruitsList().add("Banana"); System.out.println(fr.getFruitsList()); System.out.println(frCopy.getFruitsList()); } }

The output of the supra programme is:

[Mango, Orange] [Mango, Orange, Apple] [Mango, Orange, Apple] [Mango, Orange, Apple, Banana]

Notice that erstwhile transcript constructor is used, some the original entity and its transcript are unrelated to each different and immoderate modifications successful 1 of them will not bespeak into other. That’s each for the constructor successful java.

Advanced Use Cases of Constructors successful Frameworks

Constructors successful Spring and Hibernate

Constructors play a important domiciled successful Java frameworks specified arsenic Spring and Hibernate:

  1. Spring Framework: Uses constructor injection to enforce dependency management, peculiarly for immutable beans.

    @Component public class UserService { private final UserRepository userRepository; @Autowired public UserService(UserRepository userRepository) { this.userRepository = userRepository; } }
  2. Hibernate ORM: Hibernate ORM uses default (no-argument) constructors to instantiate objects erstwhile retrieving information from the database. The default constructor is basal because Hibernate creates objects utilizing reflection and needs a measurement to instantiate an entity earlier mounting its properties.

    import jakarta.persistence.*; @Entity @Table(name = "users") public class User { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String name; private String email; public User() { } public User(String name, String email) { this.name = name; this.email = email; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } }

FAQs

1. What is simply a constructor successful Java?

A constructor successful Java is simply a typical method that initializes objects. It is automatically called erstwhile an entity is instantiated. Unlike regular methods, constructors do not person a return type, not moreover void. Constructors thief successful mounting up first values for entity properties and guarantee that an entity is successful a valid authorities from the beginning.

2. What are the 4 types of constructors successful Java?

Java supports different types of constructors, which include:

  • Default Constructor – A no-argument constructor that initializes lawsuit variables pinch default values.
  • Parameterized Constructor – Allows passing arguments to group first values for entity properties.
  • Copy Constructor – Creates a caller entity by copying an existing object’s values.
  • Private Constructor – Restricts entity instantiation from extracurricular the class, commonly utilized successful the Singleton pattern. You tin mention to this tutorial connected Builder Design Pattern successful Java.

3. Why usage a constructor alternatively of a method?

Constructors and methods disagree successful purpose. A constructor is called automatically erstwhile an entity is created, ensuring due initialization. Methods, connected the different hand, must beryllium explicitly invoked and are utilized to specify behavior. Additionally, a constructor cannot return a value, whereas methods tin return results based connected business logic.

FeatureConstructorsMethods
Purpose Initialize objects Define behavior
Invocation Automatically called Explicitly invoked
Return Type No return type Can return a value
Overloading Yes Yes
Overriding No Yes
Access Modifiers Yes Yes
Static No Yes
Final No Yes
Abstract No Yes
Synchronized No Yes

4. What is the quality betwixt a constructor and an entity successful Java?

  • A constructor is simply a artifact of codification wrong a people that initializes an object.
  • An object is an lawsuit of a people created utilizing the caller keyword.
  • The constructor is executed only once per entity creation, while objects persist successful representation and tin beryllium utilized aggregate times.
FeatureConstructorsObjects
Purpose Initializes objects Represents an lawsuit of a class
Creation Executed erstwhile per entity creation Created utilizing the caller keyword
Duration Executes once Persists successful representation and tin beryllium utilized aggregate times
Role Sets first authorities of an object Represents a real-world entity aliases concept

5. What is the use of utilizing a constructor successful Java?

Constructors supply aggregate benefits, including:

  • Automatic Object Initialization: Ensures an entity starts successful a valid state.
  • Code Reusability: Reduces redundancy by centralizing initialization logic.
  • Encapsulation & Immutability: Used successful frameworks for illustration Spring and Hibernate to enforce dependency injection and configuration settings. You tin mention to this tutorial connected Java Reflection Example.

Conclusion

Constructors are an basal portion of Java programming, playing a important domiciled successful entity initialization and people design. From elemental default constructors to much precocious constructor chaining and dependency injection successful frameworks for illustration Spring and Hibernate, knowing really constructors activity tin thief developers build robust, maintainable applications.

By leveraging constructors effectively, you tin enforce immutability, beforehand reusability, and optimize performance.

You tin cheque retired these related tutorials to study more:

  • Builder Design Pattern successful Java
  • Java Reflection Example Tutorial
  • Scanner Class successful Java
More