23
NovBlack Friday Deal : Up to 40% OFF! + 2 free self-paced courses + Free Ebook - SCHEDULE CALL
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.
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
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:
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();
Java programmers can use below types of constructors:
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
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”);
}
}
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:
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
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:
Related Post
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?
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.
Cyber Security
QA
Salesforce
Business Analyst
MS SQL Server
Data Science
DevOps
Hadoop
Python
Artificial Intelligence
Machine Learning
Tableau
Search Posts
Related Posts
Receive Latest Materials and Offers on Java Course
Interviews