13
DecConstructors in Java - Types of Constructors [With Examples]
Java Constructor: An Overview
Java Constructors are important for developers who want to initialize objects in a controlled and efficient manner. Imagine having the ability to define how an object is created, ensuring that all its fields are properly initialized from the start. Constructors in Java allow you to set up objects with specific initial states, supporting features like overloading and chaining to accommodate different initialization scenarios.
In this Java tutorial, I’ll explain the different types of Constructors, how they simplify object creation by enabling flexible initialization patterns, and why mastering them is key to writing robust, maintainable Java applications.
What is Constructor in Java?
- Constructors in Java are special methods that allow the developer to create objects with specific parameters from classes.
- Polymorphism in Java Constructors has no return values, and they usually have the same name as the class.
- Initializing object member variables in constructors is not required, but quick object setup is advised.
- They accept arguments to customize object behavior and allow the passing of initial data during instance formation.
- These are essential for effective software development in Java and other languages using Object-Oriented Programming.
For example, a default constructor initializes an object with default values, while a parameterized constructor sets specific values provided by the user. Constructors make it easier to create and initialize objects in a controlled, predictable way, leading to more structured and maintainable code.
Read More - Top 50 Java Programming Interview Questions
Need of Constructors in Java
- Java constructors and methods are similar, but there are some important distinctions.
- Constructors cannot have a return type and must have the same name as the class.
- They don't require manual calling because they are automatically called when an object is created.
- Constructors are crucial for initializing objects with default or initial states.
- They give us the ability to set particular values for object properties, guaranteeing that they don't rely on primitive default values.
- Additionally, constructors provide information about class dependencies.
- You may learn what dependencies a class needs for proper usage by looking at its constructor.
Rules for Creating Java Constructors
There are a few rules that govern the creation and usage of constructors in Java.
- Same Name as Class: The name of a constructor and the class in which it is defined must match. This guarantees that it is called automatically upon the creation of a class object.
- No Return Type: Not even void serves as a return type for constructors. They don't return a value. Instead, their main function is to initialize the object.
- Parameterless or Parameterized: Java supports both parameterized and parameterless (default) constructors, giving developers freedom in how they initialize objects.
- Implicit Constructor: Java automatically offers a default constructor with no parameters if no constructor is specified in a class. The object is initialized with default values using this default constructor.
- Constructor Overloading: Constructor overloading is the ability to create multiple constructors with distinct argument lists within a class, hence providing many methods for initializing an object.
- Constructor chaining: Constructors can use the this() keyword to invoke other constructors within the same class. Constructor chaining is the term for this technique, which promotes code reuse.
- Call to Super(): When a class extends another class, super() is used to call the parent class' constructor. This guarantees that the base class properties are initialized correctly.
Example of constructor program in Java Compiler
public Employee() {
System.out.println("Employee Constructor");
}
public Employee Employee() {
System.out.println("Employee Method");
return new Employee();
}
The "Employee Constructor" text is printed whenever an instance of the "Employee" class is created in the first code block. By accident, the second block tries to define a method with the same name, but it isn't recognized as a constructor and instead returns a new "Employee" object while writing "Employee Method."
Types of constructor in Java
There are three types of constructors in Java, which are
- Default constructor in Java
- No arguments constructor in Java
- Parameterized constructor in Java
1.) Default Constructor in Java
- Default Constructors in Java are powerful tools for initializing fields in a class and object in Java.
- They are typically declared without any arguments, allowing the compiler to automatically create the constructor when an instance of the class is created.
- Default Constructors are particularly useful for setting default values, such as 0 and null, where appropriate.
- Additionally, Default Constructors enable developers to allow for custom initialization code for optional parameter values, allowing them to set up objects with more specific settings that the user or program may require.
- Default Constructors are invaluable components of object-oriented programming and can help reduce development time and complexity.
Default Constructor in Java: Example
public class MyClass {
int myInt;
String myString;
// Default constructor
public MyClass() {
myInt = 0;
myString = "default";
}
public void display() {
System.out.println("myInt = " + myInt);
System.out.println("myString = " + myString);
}
public static void main(String[] args) {
MyClass obj = new MyClass();
obj.display();
}
}
Explanation
- The default constructor of this Java class, "MyClass," initializes "myInt" to 0 and "myString" to "default."
- The values of these variables can likewise be printed using the "display" method.
- The "main" method creates an instance of "MyClass," initializes it with the constructor, and then calls the "display" method to output the contents of its member variables.
Output
myInt = 0
myString = default
2.) No argument constructor in Java
- In Java, no argument constructors allow objects to be initialized with no data passed into them.
- A no-argument constructor is usually used when no information is needed to initialize the object.
- However, this type of constructor can create potential issues if certain conditions must be met before setting up an object.
- For example, an invariant may need to be set right away, or a reference may need to be provided for the object to behave as expected.
- If a no-argument constructor is being utilized and these conditions are not met, there can sometimes be issues in other parts of the code.
- It is for this reason that Java developers often opt for more controlled methods of constructing objects via alternative ways, such as overloaded constructors or factory methods, instead of no-argument constructors.
No argument constructor in Java: Example
public class Person {
private String name;
private int age;
// Default constructor
public Person() {
this.name = "John Doe";
this.age = 30;
}
// Method to print a greeting message
public void sayHello() {
System.out.println("Hello, my name is " + this.name + " and I am " + this.age + " years old.");
}
// Main method to test the Person class
public static void main(String[] args) {
// Create an instance of the Person class
Person john = new Person();
// Call the sayHello method to print the greeting message
john.sayHello();
}
}
Explanation
- The "name" and "age" private member variables in this Java class, "Person," are initialized to "John Doe" & 30, respectively, by default in the constructor.
- Additionally, it provides a "sayHello" method that uses these settings to print a welcome message when you execute this code in the Java Online Compiler.
Output
Hello, my name is John Doe and I am 30 years old.
3.) Parameterized constructor in Java
- Parameterized constructors in Java allow developers to provide more flexibility when constructing objects.
- These constructors accept arguments that can be used to initialize the object's state.
- Parameterized constructors can be overloaded, allowing more than one version with different parameter lists to be called for various use cases.
- This is especially helpful for classes that represent complex objects that need to be initialized from different sets of information.
- The parameterized constructor also allows subclasses to call the superclass constructor and provide the necessary information required to create an instance of the subclass, making it easy to create a hierarchy of objects within programs.
- Parameterized constructors are a key concept laying at the foundation of object-oriented programming in Java and are incredibly useful when it comes to efficiently creating and organizing many types of data.
Parameterized constructor in Java: Example
class Person {
private String name;
private int age;
// Constructor to initialize name and age
public Person(String name, int age) {
this.name = name;
this.age = age;
}
// Method to print person's information
public void printInfo() {
System.out.println("Name: " + name);
System.out.println("Age: " + age);
}
}
public class Main {
public static void main(String[] args) {
// Create instances of Person class
Person person1 = new Person("John Doe", 30);
Person person2 = new Person("Jane Doe", 25);
// Print information of each person
person1.printInfo();
person2.printInfo();
}
}
Explanation
- The "name" and "age" fields of the "Person" class are set using a parameterized constructor in this Java code.
- It creates two "Person" objects in the "Main" class with different values: "John Doe" and 30 for person1, and "Jane Doe" and 25 for person2, then uses the "printInfo" function to display their respective information.
Output
Name: John Doe
Age: 30
Name: Jane Doe
Age: 25
Read More - Java Developer Salary
Private Constructor in Java
- A private constructor in Java is a special type of constructor that is only accessible to the class that is defining it.
- This type of constructor was created to give developers more control over how objects are instantiated within their programs.
- By using private constructors, a developer can ensure that their objects are always created in a predetermined manner, as private constructors cannot be called from outside the class.
- Furthermore, private constructors can help prevent duplicate objects from being created, preventing potential bugs and errors from arising.
- Private constructors offer a powerful tool for Java developers looking for better control over their code and object instantiation.
Private Constructor in Java: Example
class MyClass {
private static MyClass instance;
// Private constructor to prevent instantiation from outside
private MyClass() {
// private constructor
}
// Static method to get the singleton instance of MyClass
public static MyClass getInstance() {
if (instance == null) {
instance = new MyClass();
}
return instance;
}
// Method to display a message
public void showMessage() {
System.out.println("Hello, World!");
}
}
public class Main {
public static void main(String[] args) {
// Get the singleton instance of MyClass
MyClass myInstance = MyClass.getInstance();
// Call the showMessage method to display the message
myInstance.showMessage();
}
}
Explanation
- "MyClass," a Java class, uses the Singleton design pattern.
- The public static method "getInstance()" makes sure that just one instance of the class is created and makes sure that you may access it.
- The "Hello, World!" message is displayed when the singleton instance calls the "showMessage()" method.
Output
Hello, World!
Constructor Chaining in Java
- Constructor chaining in Java is a technique of calling one constructor from another constructor within the same class or subclass.
- It is used to minimize code duplication and improve readability by designing constructor methods with multiple parameters.
- This constructor chaining allows a programmer to set object properties quickly and effectively during object creation.
- Constructor chaining allows arguments to be passed among constructors, creating aliases for a constructor or even using default values when needed.
- By using constructor chaining, a programmer can easily utilize the full potential of Object-Oriented Programming in Java.
Constructor Chaining in Java: Example
public class Car {
private String make;
private String model;
private int year;
public Car() {
this("Unknown", "Unknown", 0);
}
public Car(String make) {
this(make, "Unknown", 0);
}
public Car(String make, String model) {
this(make, model, 0);
}
public Car(String make, String model, int year) {
this.make = make;
this.model = model;
this.year = year;
}
public void printCarDetails() {
System.out.println("Make: " + make);
System.out.println("Model: " + model);
System.out.println("Year: " + year);
}
public static void main(String[] args) {
Car car1 = new Car();
car1.printCarDetails();
Car car2 = new Car("Ford");
car2.printCarDetails();
Car car3 = new Car("Toyota", "Camry");
car3.printCarDetails();
Car car4 = new Car("Tesla", "Model S", 2022);
car4.printCarDetails();
}
}
Explanation
- This Java class, "Car," offers numerous constructors with various levels of parameterization to create car objects with make, model, and year properties.
- It shows how to create vehicle instances with various constructor overloads in the "main" method and uses the "printCarDetails" method to print their information.
Output
Make: Unknown
Model: Unknown
Year: 0
Make: Ford
Model: Unknown
Year: 0
Make: Toyota
Model: Camry
Year: 0
Make: Tesla
Model: Model S
Year: 2022
Super Constructor in Java
- Super Constructor in Java is a particular type of constructor that allows the subclass to invoke the Superclass constructor.
- It is used when an object is being inherited from another class, and its subclasses need additional values that are specific to itself.
- Super Constructor can be used to create a thing of the Superclass with a set of parameters different from those specified in its Superclass by calling it Super().
- Super Constructor is useful for assigning different values to instance variables of Superclass, which may be required during subclass initialization.
- As a result, super constructors provide a greater level of flexibility while dealing with complex hierarchies.
Super Constructor in Java: Example
class Animal {
String name;
int age;
public Animal(String name, int age) {
this.name = name;
this.age = age;
}
public void displayInfo() {
System.out.println("Name: " + name);
System.out.println("Age: " + age);
}
}
class Dog extends Animal {
String breed;
public Dog(String name, int age, String breed) {
super(name, age);
this.breed = breed;
}
public void displayInfo() {
super.displayInfo();
System.out.println("Breed: " + breed);
}
}
public class Main {
public static void main(String[] args) {
Dog myDog = new Dog("Fido", 3, "Labrador");
myDog.displayInfo();
}
}
Explanation
- In the above-written code in Java Online Editor, there is a superclass called "Animal" and a subclass called "Dog."
- Name and age can be set in the "Animal" class constructor, and the method "displayInfo" can report these details.
- The "breed" attribute is an extension of "Animal" added by the "Dog" class. The "Dog" instance is created, its attributes are initialized, and the data, including the breed, is displayed in the "main" method.
Output
Name: Fido
Age: 3
Breed: Labrador
Copy Constructor in Java
- Copy Constructor in Java is a special type of constructor used to create a replica of an existing object.
- This type of constructor helps to reduce code redundancy and make programs more maintainable.
- Copy Constructors are a deep copy operation, meaning that all the member variables are copied by value rather than by reference.
- Copy Constructors are particularly useful when the user needs to create backup copies of objects before performing manipulation operations on them.
- Copy Constructor objects can also be used as handy return values from methods that create custom copies of classes.
- Copy Constructors can be quite powerful in achieving maximum code re-usability in Java applications.
Copy Constructor in Java: Example
class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
// Copy constructor
public Person(Person other) {
this.name = other.name;
this.age = other.age;
}
public void display() {
System.out.println("Name: " + this.name);
System.out.println("Age: " + this.age);
}
}
public class Main {
public static void main(String[] args) {
Person person1 = new Person("John", 30);
Person person2 = new Person(person1); // Using copy constructor
person1.display();
person2.display();
}
}
Explanation
- This Java example creates a "Person" class with a copy constructor that allows you to duplicate the attributes of an existing "Person" object to create a new "Person" object.
- The "main" method shows how to create "person1" and "person2" by copying "person1's" attributes, and then it displays the data for both "person1" and "person2."
Output
Name: John
Age: 30
Name: John
Age: 30
How do you copy values without a constructor in Java?
In Java, you can copy values from one object to another without using a constructor by implementing a method specifically for this purpose. One common approach is to create a process that takes an instance of the source object and copies its values to the destination object.
Example
class MyClass {
private int value;
// Getter and Setter methods
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
// Method to copy values
public void copyValues(MyClass source) {
this.value = source.getValue();
}
public static void main(String[] args) {
MyClass sourceObject = new MyClass();
sourceObject.setValue(10);
MyClass destinationObject = new MyClass();
destinationObject.copyValues(sourceObject);
System.out.println("Value in destination object: " + destinationObject.getValue());
}
}
Output
Value in destination object: 10
Explanation
- This Java program defines a class MyClass with a field value and methods to get, set, and copy the value from another object.
- The copyValues() method assigns the value of one MyClass object (source) to another (destination).
- The main method demonstrates copying the value 10 from sourceObject to destinationObject and then printing it.
What Is Constructor Overloading in Java?
The process of defining multiple constructors of the same class is referred to as Constructor overloading in Java. The important thing is that each constructor should have a different signature or input parameters. In other words, constructor overloading in Java is a technique that allows a single class to have more than one constructor that varies by the list of arguments passed. Each overloaded constructor performs different tasks in the class.
The Java compiler identifies the overloaded constructors based on their parameter lists, parameter types, and the number of input parameters. Hence, the overloaded constructors should have different signatures. A constructor’s signature contains its name and parameter types.
Using this() in Constructor Overloading
All instance methods and constructors have an implicit parameter called ‘this’, which is used to refer to the current object. The current object is the object on which the method is invoked. We can use the ‘this’ reference to refer to the current object within any constructor or method.
In the following cases, the ‘this’ reference is used:
- When the names of the parameters are different from the instance variable names
- When a reference is to be passed to the current object and a parameter to another method
- When a constructor is to be invoked from another constructor.
Example
public class MyClass {
private int value;
// Default constructor
public MyClass() {
this.value = 0; // Initialize value to 0
}
// Constructor with one parameter
public MyClass(int value) {
this.value = value; // Initialize value to the provided parameter
}
// Constructor with two parameters
public MyClass(int value1, int value2) {
this.value = value1 + value2; // Initialize value to the sum of the two parameters
}
// Getter method
public int getValue() {
return value;
}
public static void main(String[] args) {
// Creating objects using different constructors
MyClass obj1 = new MyClass();
MyClass obj2 = new MyClass(5);
MyClass obj3 = new MyClass(3, 7);
// Displaying values
System.out.println("Value in obj1: " + obj1.getValue());
System.out.println("Value in obj2: " + obj2.getValue());
System.out.println("Value in obj3: " + obj3.getValue());
}
}
Output
Value in obj1: 0
Value in obj2: 5
Value in obj3: 10
Difference between constructor and method in Java
Feature | Constructor | Method |
Purpose | Used to initialize an object. | Used to perform some operation or action. |
Name | Same as the class name. | It can have any valid name, usually action-related. |
Return Type | No return type (not even void ). | It must have a return type void if no value is returned. |
Invocation | Automatically called when an object is created. | The user is called explicitly to perform an action. |
Inheritance | It cannot be inherited by subclasses. | It can be inherited and overridden by subclasses. |
Default | If no constructor is provided, Java provides a default constructor. | No default methods are provided by Java. |
Overloading | It can be overloaded by defining multiple constructors with different parameters. | It can be overloaded with multiple methods with different parameters. |
Use | Primarily used for object creation and initialization. | Used to define the behavior of objects. |
Summary
After learning about Java Constructors, the constructor in Java, the constructor in Java example, and the use of constructors in Java, java constructor, we see that they are fundamental tools that every beginner programmer should understand. They allow us to create objects by passing in specific data needed, which helps reduce complexity and time spent coding. Although the syntax may be difficult for Java for beginners to grasp at first, with practice, it becomes second nature. Constructors are essential for all types of application development and can save developers both time and stress when used effectively.
FAQs
Java does not have explicit destructors like C++. Java uses automatic garbage collection to reclaim memory occupied by objects that are no longer referenced.