Constructor in Java

Video Tutorial
FREE
Constructor thumbnail
This video belongs to
Java Course - Mastering the Fundamentals
12 modules
Certificate
Topics Covered

In Java, Constructors initialize the state of an object during the time of object creation. The constructor in java is called when an object of a class is created. Constructors must have the same name as the class within which it is defined.

What is Constructor in Java?

A constructor in Java, in the simplest terms, is a specialized method responsible for initializing an object. It is called at the time of object creation and can be used to set initial values of an object's data members.

Syntax:

Syntax is pretty straightforward. It is the same as how one would define a class but without the class keyword.

This is the syntax for the class:

This is the syntax for its constructor:

Classes are blueprints of objects specifying an object's various fields and methods. However, constructors in Java are specialized methods that can be used to assign values to those fields.

Let’s look at the code snippet below:

Output:

Explanation:

“new” is a java keyword that is used to create an instance of the class. dog3 of type Dogs equals a ‘new’ Dogs with name = "Snoopy" and breed = "German Shepherd". The dog dog3 is initialized with these parameters.

new Dogs(name, breed) is a call to the constructor. The parameters name and breed represent the initial state of the new object being created.

Rules for Creating Java Constructor

There are some important and basic rules to create a constructor in Java.

  • Constructor names are always the same as the class name.
  • Constructors never have a return type.
  • There are four keywords in Java that is NEVER associated with a constructor – abstract, final, static, and synchronized.
  • Constructors in Java are, therefore, also called special methods, which are invoked automatically at the time of object creation.

Transform Your Career

Choose from our industry-leading programs designed for career success

NSDC Certified

Modern Software and AI Engineering Program

Master full-stack development with AI integration

12 MonthsDuration
AI-LedCurriculum
Career SupportSupport
GoogleAmazonPaytm+1000 more
Go to Program
NSDC Certified

Modern Data Science and ML with specialisation in AI

Advanced data science techniques with AI specialization

12 MonthsDuration
AI-LedCurriculum
Career SupportSupport
GoogleAmazonPaytm+1000 more
Go to Program
NSDC Certified

Advanced AIML with Specialisation in Agentic AI

Deep dive into AIML with focus on Agentic systems

12 MonthsDuration
AI-LedCurriculum
Career SupportSupport
GoogleAmazonPaytm+1000 more
Go to Program
NSDC Certified

DevOps, Cloud & AI Platform Engineering

Build and manage AI-powered cloud infrastructure

12 MonthsDuration
AI-LedCurriculum
Career SupportSupport
GoogleAmazonPaytm+1000 more
Go to Program
NSDC Certified

AI Engineering Advanced Certification by IIT-Roorkee

Premier AI engineering certification from IIT-Roorkee

3 MonthsDuration
AI-LedCurriculum
Career SupportSupport
Program highlights
Go to Program

Types of Constructor in Java

Default Constructor (No-Arg Constructors)

As the name suggests, these constructors do not have any arguments since they are created by default in Java when the programmer writes no constructors.

Consider the example of the Dogs class.

Output:

Explanation:

In the above code snippet, there are no constructors defined. In such a case, Java would automatically create a constructor without parameters. Hence, it is also called the default constructor. It does not initialize any member of the class. It simply creates the object with no initial state.

Parameterized Constructor

In this case, the programmer writes the constructors with one or more arguments. This allows distinct or same values to be assigned to the object’s data member during object creation.

Constructor Overloading in Java

In Java, constructors are similar to methods but without a return type. They can be overloaded, just like methods, allowing for the creation of multiple constructors with different parameter lists. Each constructor can serve a distinct purpose, with the compiler distinguishing them based on the number and types of parameters they accept. This technique, known as constructor overloading, enables flexibility in initializing objects based on varying sets of input parameters.

Output:

Now, if one wanted to create an object of type Dogs with the same name or say with name and breed, they would be able to.

They are different in the number of parameters, and they are the same in that all of them allow for object creation, although with some differences.

Turn Learning into Career Growth

1200+Hiring Partners
89%Placement Rate
11,000+Placements
147%Avg Salary Increment
2.5XCareer Growth
₹23 LPAAvg Post-Scaler Salary
1200+Hiring Partners
89%Placement Rate
11,000+Placements
147%Avg Salary Increment
2.5XCareer Growth
₹23 LPAAvg Post-Scaler Salary

Difference between Constructors and Methods in Java

The table below has the differences between constructors and methods listed out:

ConstructorsMethods
Constructors always have the same name as the class for which they are being created.Method names could be anything but the class name.
Constructors never have any return type.Methods can return any value or nothing by using the keyword void.
The usage of a constructor in Java is minimal compared to a method. It is called only when the object of a class is created, while methods can be called whenever. Constructors are invoked implicitly.Methods can be called whenever the programmer desires them. Methods are called explicitly.
Functionality-wise, constructors are used to initialize an objectMethods are used to execute a specific operation.
A constructor would be created by default if the user provides noneMethods must be created.

Copy Constructor in Java

A Copy Constructor in Java is used to create an object with the help of another object of the same Java class.

Let’s say we create an object using the copy constructor. The copy constructor has at least one object of the same class as an argument. The primary objective of the copy constructor is to create a new object with the same properties as that of the passed argument.

Look at the code snippet below:

dog2 is created using the copy constructor where dog1 is passed as an argument. The data members of dog2 are initialized using the data members of the dog1.

How to Copy Values without Constructor?

We can achieve object value copying without using a constructor in java by directly assigning the values of one object to another.

In this example, we have a class called Dog with two fields: age and name. We've defined a constructor to initialize these fields, along with a default constructor and a method display() to print the values of the fields.

Output

Scaler Placement Report and Statistics

₹23L
AVG CTC
SCALER PLACEMENT PROOF

Scaler learners achieved 2.5x salary growth with average post-Scaler CTC reaching ₹23L.

11,000+placements
650+companies
Verified data

Conclusion

  • Constructor in Java is used to initialize the data members of an object at the time of object creation.
  • There are two major types of constructors in Java: Parameterized and No-Arg constructors.
  • The No-Arg constructors in Java are created by default in Java and take no arguments.
  • The Parameterized constructer can be used to pass values, allowing values to be assigned to the state of an object during creation.
  • The copy constructor in Java is a constructor that creates an object by initializing it with an object of the same class that has been created previously.

FAQs

Q: What is this () in Java constructor?

A: In Java, the parentheses () in a constructor declaration represent the parameter list the constructor may accept.

Q: What is the difference between a constructor and a destructor?

A: A constructor is called when an object is created, while when an object is destroyed or goes out of scope, then the destructor is called.

Hiring Partners:
GoogleGoogleAmazonAmazonMicrosoftMicrosoftFlipkartFlipkartAdobeAdobe1200+ more