Introduction
Understanding Constructors is essential to utilizing this powerful programming language. Constructors in Java are a special type of method that can help create an object and assign values to its instance variables upon its initialization.
In addition, constructors ensure that only one instance or “copy” of each object exists at a given time due to their unique ability to initialize data and variable states for them to be properly used within different class methods should they require such information again.
Java constructors or constructors in Java is a terminology used to construct something in our programs. A constructor in Java is a special method that is used to initialize objects. The constructor is called when an object of a class is created. It can be used to set initial values for object attributes.
Constructors in Java
In Java, a Constructor is a block of codes similar to the method. It is called when an instance of the class is created. At the time of calling the constructor, memory for the object is allocated in the memory. It is a special type of method that is used to initialize the object. Every time an object is created using the new() keyword, at least one constructor is called.
Syntax
public class MyClass {
// Constructor
public MyClass() {
// Initialization code goes here
}
// Other methods and variables can be defined here
}
JavaHow Java Constructors are Different From Java Methods?
- Constructors must have the same name as the class within which it is defined it is not necessary for the method in Java.
- Constructors do not return any type while method(s) have the return type or void if does not return any value.
- Constructors are called only once at the time of Object creation while method(s) can be called any number of times.
Need of Constructors in Java
Think of a Box. If we talk about a box class then it will have some class variables (say length, breadth, and height). But when it comes to creating its object(i.e Box will now exist in the computer’s memory), then can a box be there with no value defined for its dimensions? The answer is No.
So constructors are used to assign values to the class variables at the time of object creation, either explicitly done by the programmer or by Java itself (default constructor).
Rules for creating Java constructor
There are two rules defined for the constructor.
- The constructor name must be the same as its class name
- A Constructor must have no explicit return type
- A Java constructor cannot be abstract, static, final, and synchronized
Note:
We can use access modifiers while declaring a constructor. It controls the object creation. In other words, we can have private, protected, public or default constructor in Java.
Types of Java Constructors
- Default constructor: These constructors do not accept any parameters.
- Parameterized constructor: These constructors accept a specific number of parameters.
Default Constructor
In Java, if a class does not explicitly define any constructors, the compiler automatically provides a default constructor. This default constructor is parameterless (i.e., it takes no arguments) and initializes member variables to their default values.
Here’s an example of a default constructor in Java:
public class MyClass {
private int myInt;
private String myString;
// This class does not define any constructors
public static void main(String[] args) {
// Creating an object of MyClass using the default constructor
MyClass obj = new MyClass();
// Accessing member variables
System.out.println("Default value of myInt: " + obj.myInt);
// Output: Default value of myInt: 0
System.out.println("Default value of myString: " + obj.myString);
// Output: Default value of myString: null
}
}
JavaIn this example, MyClass
does not define any constructors explicitly. Therefore, Java automatically provides a default constructor for MyClass
. When an object of MyClass
is created using the new
keyword without passing any arguments, the default constructor is invoked. This default constructor initializes the myInt
member variable to 0
(default value for int
) and the myString
member variable to null
(default value for String
).
Parameterized Constructor
A parameterized constructor in Java is a constructor that accepts one or more parameters, allowing you to initialize objects with specific values. Unlike the default constructor, which takes no arguments, a parameterized constructor allows you to pass values at the time of object creation to set initial states.
Here’s an example of a parameterized constructor in Java:
public class MyClass {
private int myInt;
private String myString;
// Parameterized constructor
public MyClass(int intValue, String stringValue) {
myInt = intValue;
myString = stringValue;
}
// Method to display values
public void displayValues() {
System.out.println("myInt: " + myInt);
System.out.println("myString: " + myString);
}
public static void main(String[] args) {
// Creating an object of MyClass using the parameterized constructor
MyClass obj = new MyClass(10, "Hello");
// Displaying the initialized values
obj.displayValues();
}
}
JavaIn this example, the MyClass
constructor MyClass(int intValue, String stringValue)
is parameterized, taking an integer intValue
and a string stringValue
. Inside the constructor, these parameters are used to initialize the myInt
and myString
member variables of the object being created.
When an object of MyClass
is created using this parameterized constructor, values are passed for intValue
and stringValue
. These values are then used to initialize the member variables myInt
and myString
, respectively.
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.
class Dogs {
private String name;
private String breed;
public Dogs() {
// No initialization parameters
}
public Dogs(String breed) {
this.breed = breed;
}
public Dogs(String name, String breed) {
this.name = name;
this.breed = breed;
}
void isRunning(int runStatus) {
if (runStatus == 1) {
System.out.println("Dog is running");
} else {
System.out.println("Dog is not running");
}
}
}
public class Main {
public static void main(String[] args) {
Dogs dog1 = new Dogs();
Dogs dog2 = new Dogs("Bulldog");
dog1.isRunning(0);
dog2.tailWagging("Woof");
// A dog with both name and breed initialized at the time of object creation.
Dogs dog3 = new Dogs("Snoopy", "German Shepherd");
}
}
JavaOutput:
Dog is not running
Dog is wagging its tail
JavaCopy 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.
public class MyClass {
private int myInt;
private String myString;
// Copy constructor
public MyClass(MyClass original) {
this.myInt = original.myInt;
this.myString = original.myString;
}
// Parameterized constructor
public MyClass(int intValue, String stringValue) {
this.myInt = intValue;
this.myString = stringValue;
}
// Method to display values
public void displayValues() {
System.out.println("myInt: " + myInt);
System.out.println("myString: " + myString);
}
public static void main(String[] args) {
// Creating an object of MyClass
MyClass originalObj = new MyClass(10, "Hello");
// Creating a copy of originalObj using the copy constructor
MyClass copiedObj = new MyClass(originalObj);
// Displaying values of both objects
System.out.println("Original Object:");
originalObj.displayValues();
System.out.println("nCopied Object:");
copiedObj.displayValues();
}
}
JavaIn this example, MyClass
defines a copy constructor MyClass(MyClass original)
that takes an object of the same class as its parameter. Inside the copy constructor, the state of the new object (copiedObj
) is initialized by copying the values of the member variables from the existing object (originalObj
). As a result, copiedObj
is created with the same state as originalObj
, but they are distinct objects in memory.
Constructor Chaining in Java
Constructor chaining in Java refers to the process of one constructor calling another constructor from the same class. This allows for code reuse and centralization of initialization logic within a class. In Java, constructor chaining is achieved using the this()
keyword to call another constructor within the same class.
Here’s an example demonstrating constructor chaining in Java:
public class MyClass {
private int myInt;
private String myString;
// Parameterless constructor (constructor 1)
public MyClass() {
// Calling parameterized constructor with default values
this(0, "Default");
}
// Parameterized constructor with int parameter (constructor 2)
public MyClass(int intValue) {
// Calling parameterized constructor with int parameter and default string value
this(intValue, "Default");
}
// Parameterized constructor with String parameter (constructor 3)
public MyClass(String stringValue) {
// Calling parameterized constructor with default int value and String parameter
this(0, stringValue);
}
// Parameterized constructor with int and String parameters (constructor 4)
public MyClass(int intValue, String stringValue) {
myInt = intValue;
myString = stringValue;
}
// Method to display values
public void displayValues() {
System.out.println("myInt: " + myInt);
System.out.println("myString: " + myString);
}
public static void main(String[] args) {
// Creating objects of MyClass using different constructors
MyClass obj1 = new MyClass(); // Constructor 1
MyClass obj2 = new MyClass(10); // Constructor 2
MyClass obj3 = new MyClass("Hello"); // Constructor 3
MyClass obj4 = new MyClass(20, "World"); // Constructor 4
// Displaying values of each object
obj1.displayValues();
obj2.displayValues();
obj3.displayValues();
obj4.displayValues();
}
}
JavaIn this example:
- Constructor 1 is the parameterless constructor, which calls constructor 4 with default values.
- Constructor 2 is a parameterized constructor with an
int
parameter, which calls constructor 4 with the providedint
value and a defaultString
value. - Constructor 3 is a parameterized constructor with a
String
parameter, which calls constructor 4 with a defaultint
value and the providedString
value. - Constructor 4 is a parameterized constructor with both
int
andString
parameters, which initialize themyInt
andmyString
member variables with the provided values.
By using constructor chaining, we avoid duplicating initialization logic and ensure that all constructors ultimately initialize the object using constructor 4, which contains the actual initialization code.
Super Constructor in Java
In Java, the super()
constructor call is used to invoke the constructor of the superclass within a subclass constructor. This allows the subclass to initialize the inherited members of the superclass. Here’s a Java code example demonstrating the use of the super()
constructor call:
class Superclass {
private int superClassValue;
// Superclass constructor
public Superclass(int value) {
superClassValue = value;
System.out.println("Superclass constructor invoked");
}
// Method to display superclass value
public void displaySuperclassValue() {
System.out.println("Superclass value: " + superClassValue);
}
}
class Subclass extends Superclass {
private int subclassValue;
// Subclass constructor
public Subclass(int superClassValue, int subclassValue) {
super(superClassValue); // Calling superclass constructor
this.subclassValue = subclassValue;
System.out.println("Subclass constructor invoked");
}
// Method to display subclass value
public void displaySubclassValue() {
System.out.println("Subclass value: " + subclassValue);
}
}
public class Main {
public static void main(String[] args) {
// Creating an object of Subclass
Subclass obj = new Subclass(10, 20);
// Displaying values using superclass and subclass methods
obj.displaySuperclassValue();
obj.displaySubclassValue();
}
}
JavaIn this example:
Superclass
has a constructor that initializes a private membersuperClassValue
.Subclass
extendsSuperclass
and has its own constructor that initializes a private membersubclassValue
. It calls the constructor of the superclass usingsuper(superClassValue)
to initialize the inherited membersuperClassValue
.- When an object of
Subclass
is created, both the superclass constructor and the subclass constructor are invoked in sequence. - The
displaySuperclassValue()
anddisplaySubclassValue()
methods are used to display the values of the superclass and subclass members, respectively.
Conclusion
Java constructors play a vital role in object-oriented programming by facilitating the initialization of objects within classes. They ensure that objects are properly initialized with appropriate initial values, contributing to the integrity and reliability of Java programs. Key points to remember about Java constructors include:
- Constructors are special methods with the same name as the class, used for initializing objects.
- They do not have a return type, not even
void
. - Java provides default constructors if no constructors are explicitly defined in a class.
- Constructor overloading allows for multiple constructors with different parameter lists within the same class.
- Constructor chaining enables one constructor to call another constructor within the same class using the
this()
keyword. - The
super
keyword is used to explicitly call the constructor of the superclass within a subclass constructor. - Constructors can have access modifiers like
public
,protected
, orprivate
. - Constructors are not inherited but are invoked when objects of subclasses are created.
- Constructors cannot be abstract or static in Java.
Understanding constructors is essential for creating well-structured and maintainable Java code, as they provide a means to ensure objects are properly initialized and ready for use. By mastering the concepts and best practices related to constructors, Java developers can write more efficient and reliable software applications.
Frequently Asked Questions
A constructor in Java is a special type of method that is automatically called when an instance of a class is created. Its main purpose is to initialize the newly created object.
A constructor has the same name as the class and does not have a return type, not even void
. Here’s an example: public MyClass() { ... }
.
If a class does not explicitly define any constructors, Java provides a default constructor. This default constructor initializes member variables to their default values.
Constructor overloading in Java refers to the practice of defining multiple constructors within a class, each with a different parameter list. This allows objects to be initialized in different ways.
Constructor chaining in Java is the process of one constructor calling another constructor from the same class using the this()
keyword. This allows for code reuse and centralization of initialization logic within a class.