Black Friday Deal : Up to 40% OFF! + 2 free self-paced courses + Free Ebook  - SCHEDULE CALL

- Java Blogs -

What is A Java Constructor? Type of Constructors & Uses in Java

Java constructors are used to initializing the object state that may also include methods. Constructors are used in any of the object-oriented languages that contain the statements executed at the time when an object is created. Constructors are of much use in Java and this article will discuss constructors of Java language.

The topics to be covered in the post include - Quick constructor introduction and types of constructors. The examples are also provided with each type of constructor for a better explanation. After going through the article, you will become familiarized with the constructors that are used in the Java language.

Java is a most used programming language, developers use Java to develop the programs and project that are compatible with all platforms. The user may require Java constructors if he wants to assign a few of the default values to the class members or class data members.

Although in Java the constructors are created by default, still if you want to assign any particular value to the class objects then you can use Java constructors. It is not a keyword in Java, instead, users opt them to create the methods with the help of which a default value can be assigned to the data members.

What is Java Constructor?

As it is quite clear that Java is an object-oriented programming language. It works and follows the concepts of OOPS. In any of the object-oriented language, we need to create objects so that every statement and method can get executed. Objects are the basic requirement for any of the object-oriented language. So, in Java also there are objects that are used by the developers to execute any operation. These objects can have various variables, methods, and statements associated with them.

Any of the objects can be used to execute the set of statements as they represent the complete class. When the user needs to create an object in the way so that whenever the class object is created few sets of statements get executed automatically, then in such case they can use constructors. Constructors are used to initializing an object from the desired state. Like if a user wants that whenever the object is created some of the variables get initialized or have some value.

Read: What Is Spring Framework? Spring Tutorial Guide for Beginner

A Quick Introduction Constructors in Java

When an object is created with the new keyword, then the constructor is automatically invoked by the object and the variables are assigned default values. The data members of the class are *initialized to these values. As shown in the bel**

There are a few of the rules to create the constructor of any class. The rules are to be followed to create the constructor that is listed below:

  • The name of the constructor must match with the class name or the constructor name and class name must be similar
  • Java constructors cannot be final, abstract, synchronized or static
  • While declaring constructors, access specifiers like the public, private, or protected must be used with the constructors, with which the access of the constructors can be controlled and
  • As per this, the constructors can be called and used.

Class Dummy{
- - - - - - - - 

// A Constructor
new Dummy() {  }

                - - - - - 
}
//When the object of above class will be created through following statement, above constructor will be automatically called//
Dummy newObj=new Dummy();

Types of Constructors in Java

Java programmers can use below types of constructors:

  1. Default Constructors or No-Argument
  2. Parameterized Constructor
  3. Copy Constructor

1). Default or No-Argument Constructor

The constructor that has no parameter is called default or no argument constructor. In case if no constructor is defined then a default constructor is created, that will have no argument. In case if the user creates a constructor with argument or parameter then no default constructor will be created. The default constructor is used to provide default values to the objects that can be 0, any other value or null, depending on the type of constructors.

Example of No Argument or Default Constructor: Here, in this example, we have created a class, named Dummy and a constructor with the same name is assigned to the class that has no parameter and a statement is there. When the class object will be created a value will be assigned to the object.


import java.io.*;
class Dummy
{
String name;
int num;
Dummy(String nm, int val)
{this.name=nm;
this.num=val;}
class Derived
{public static void main (String args[])
{Dummy dm=new Dummy(u, 10);                                 );
system.out.println(“Constructor values are”);
}
}

The Output of the above program will be: This is default constructor This is derived class Any constructor does not return any value, instead, they return the instance of the current class. The return statement can also be written inside the constructor.

Read: How to Resolve Java.net.ConnectException: Connection Refused Error

2). Parameterized Constructor

The constructor that has the parameters is called the parameterized constructor. They are used when we want to initialize the variables with any default value. The values that are stored in the variables can have the values equal to the parameters that are passed in the constructors. As shown in the following example:

// Example of Parameterized Java Constructor

Here in this example, the constructor of the class is parameterized and it has two arguments one is of string type and another is of numeric type.  The values are assigned to the variables at the time when the object is created.


import java.io.*;
class Dummy
{
String name;
int num;
Dummy(String nm, int val)
{this.name=nm;
this.num=val;}
class Derived
{public static void main (String args[])
{Dummy dm=new Dummy(u, 10);                                 );
system.out.println(“Constructor values are”);
}
}

3). Copy Constructors

If we want to prepare a duplicate object of the same class with same values, then for that cases a special type of constructor known as copy constructor is used. This type of constructor takes one parameter that is of class type for which we have to create the object. In the following program, we have shown the use of copy constructor and the use of that one in the program:


class Dummy {
 int val1;
int val2;
Dummy(int v1,int v2)
{
val1=v1;
val2=v2;
}
Dummy (Dummy DObj)
{
val1=DObj.val1;
val2=DObj.val2;
}
void displayValue()
{
 system.out.println(“First Value”+ val1);
system.out.println(“Second Value is” + val2);
} }
public class DummyTest 
{
public static void main(String[] args)
{
Dummy d1=new Dummy(20,40);
d1.displayValue();
Dummy d2=new Dummy(d1);
d2.displayValue();
}
}

The Output of the above program will be:

  • First Value 20
  • Second Value is 40
  • First Value 20
  • Second Value is 40

Java Constructor Overloading

Constructor overloading is just like method overloading, in case if two or more constructors are different depending on the number and types of parameters. An example is given below:

Read: A Complete ReactJS Tutorial in 2023

Class Dummy {
 String shapeName;
 Public Dummy() {
 this.shapeName=”Default is Circle”;
}
Public Dummy (String paramShapeName) {
 this.shapeName=paramShapeName;
}
Public void getName(){
Sysytem.out.println(this.shapeName);
}
Public static void main(String[] args){
 Dummy defaultObj = new Dummy();
Dummy programObj = new Dummy(“Parameter is Square”);
  defaultObj.getName();
 programObj.getName();
}
}

Here, the output of the above program will be: Default is circle Parameter is Square

Some Important Notes for the use of Constructors

Java programmers use constructors for a variety of reasons and here we have provided the details of these constructors so that you can get the complete idea of them and use them. When the constructors are created some rules are followed and for that, we must be aware of them so that user may not get confused and without any error, they can be used.

There are some of the points for the constructor that must be known while creating them, moreover, you may have to be familiar with these rules in order to use the constructors:

  • Constructors are implicitly called at the time of object creation.
  • Name of Java Constructor must be the same as that of the class name and they do not have any return type.
  • If the developer does not define any constructor then a default constructor is automatically created by the Java compiler at the runtime. In this constructor, the value of the variables is initialized with zero.
  • In the Java language, basically there are following types of constructors:
    • No-Arg Constructor: The constructor that do not have any argument or parameter is called as No argument constructor
    • Default Constructor: The constructor that is automatically created by Java compiler without any external definition is known as the default constructor
    • Parameterized Constructor: They are used to specify specific values for the object variables
  • Constructors can be overloaded and cannot be static or final.

Related Post

  1. Java Collections
  2. Declare String Array in Java
  3. What is Inheritance in Java?
  4. Java String Functions

Final Words: In this way, we can see that Java constructors are of three types and are most significant for the Java programmers. The constructors can have a default or pre-assigned values, depending on the case and requirement you can assign the values to class members by using constructors.

There are mainly two types of constructors in Java language that is parametrized and non-parameterized, but apart from that user can also use the copy constructor to copy the values of one object to another. These constructors in Java are of much use especially when you want to assign a default value to the class members. That’s all for the day! I hope you enjoyed reading this post.

Read: What is the Difference between JavaScript and JQuery?


fbicons FaceBook twitterTwitter lingedinLinkedIn pinterest Pinterest emailEmail

     Logo

    JanBask Training

    A dynamic, highly professional, and a global online training course provider committed to propelling the next generation of technology learners with a whole new way of training experience.


  • fb-15
  • twitter-15
  • linkedin-15

Comments

Trending Courses

Cyber Security Course

Cyber Security

  • Introduction to cybersecurity
  • Cryptography and Secure Communication 
  • Cloud Computing Architectural Framework
  • Security Architectures and Models
Cyber Security Course

Upcoming Class

0 day 22 Nov 2024

QA Course

QA

  • Introduction and Software Testing
  • Software Test Life Cycle
  • Automation Testing and API Testing
  • Selenium framework development using Testing
QA Course

Upcoming Class

1 day 23 Nov 2024

Salesforce Course

Salesforce

  • Salesforce Configuration Introduction
  • Security & Automation Process
  • Sales & Service Cloud
  • Apex Programming, SOQL & SOSL
Salesforce Course

Upcoming Class

0 day 22 Nov 2024

Business Analyst Course

Business Analyst

  • BA & Stakeholders Overview
  • BPMN, Requirement Elicitation
  • BA Tools & Design Documents
  • Enterprise Analysis, Agile & Scrum
Business Analyst Course

Upcoming Class

0 day 22 Nov 2024

MS SQL Server Course

MS SQL Server

  • Introduction & Database Query
  • Programming, Indexes & System Functions
  • SSIS Package Development Procedures
  • SSRS Report Design
MS SQL Server Course

Upcoming Class

1 day 23 Nov 2024

Data Science Course

Data Science

  • Data Science Introduction
  • Hadoop and Spark Overview
  • Python & Intro to R Programming
  • Machine Learning
Data Science Course

Upcoming Class

0 day 22 Nov 2024

DevOps Course

DevOps

  • Intro to DevOps
  • GIT and Maven
  • Jenkins & Ansible
  • Docker and Cloud Computing
DevOps Course

Upcoming Class

5 days 27 Nov 2024

Hadoop Course

Hadoop

  • Architecture, HDFS & MapReduce
  • Unix Shell & Apache Pig Installation
  • HIVE Installation & User-Defined Functions
  • SQOOP & Hbase Installation
Hadoop Course

Upcoming Class

0 day 22 Nov 2024

Python Course

Python

  • Features of Python
  • Python Editors and IDEs
  • Data types and Variables
  • Python File Operation
Python Course

Upcoming Class

8 days 30 Nov 2024

Artificial Intelligence Course

Artificial Intelligence

  • Components of AI
  • Categories of Machine Learning
  • Recurrent Neural Networks
  • Recurrent Neural Networks
Artificial Intelligence Course

Upcoming Class

1 day 23 Nov 2024

Machine Learning Course

Machine Learning

  • Introduction to Machine Learning & Python
  • Machine Learning: Supervised Learning
  • Machine Learning: Unsupervised Learning
Machine Learning Course

Upcoming Class

35 days 27 Dec 2024

 Tableau Course

Tableau

  • Introduction to Tableau Desktop
  • Data Transformation Methods
  • Configuring tableau server
  • Integration with R & Hadoop
 Tableau Course

Upcoming Class

0 day 22 Nov 2024

Search Posts

Reset

Receive Latest Materials and Offers on Java Course

Interviews