Constructors in Java: Types of Constructors with Examples

Shailendra Chauhan  23 min read
22 Sep 2023
Intermediate
778 Views

Constructor in Java: An Overview

When learning the fundamentals of Java for beginners, understanding Constructors is essential to utilizing this powerful programming language. Constructors 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 in order for them to be properly used within different class methods should they require such information again. So without further ado, let’s explore how Java utilizes constructors!

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 is advised for quick object setup. They accept arguments to customize object behavior and allow the passing of initial data during instance formation. essential for effective software development in Java and other languages using Object-Oriented Programming.

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.
  • For initializing objects with default or initial states, constructors are crucial.
  • 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.

Example of constructor program in Java

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 constructor in Java, which are

  1. Default constructor in Java
  2. No arguments constructor in Java
  3. Parameterized constructor in Java

Default Constructor in Java

  • Default Constructors in Java are powerful tools for initializing fields in a class and object in Java.
  • They are normally 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 may be required by the user or program.
  • Default Constructors are invaluable components of object-oriented programming and can help reduce development time and complexity.

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();
    }
}

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

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 in order to initialize the object.
  • However, this type of constructor can create potential issues if there are certain conditions that 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 in order 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.

Example

public class Person {
    private String name;
    private int age;
    public Person() {
        this.name = "John Doe";
        this.age = 30;
    }
    public void sayHello() {
        System.out.println("Hello, my name is " + this.name + " and I am " + this.age + " years old.");
    }
}

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.

Output

Hello, my name is John Doe and I am 30 years old.

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 for initializing 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.

Example

public class Person {
    private String name;
    private int age;
    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }
    public void printInfo() {
        System.out.println("Name: " + name);
        System.out.println("Age: " + age);
    }
}
public class Main {
    public static void main(String[] args) {
        Person person1 = new Person("John Doe", 30);
        Person person2 = new Person("Jane Doe", 25);
        person1.printInfo();
        person2.printInfo();
    }
}

The "name" and "age" fields of the "Person" class are set using a parameterized constructor defined in this Java code. It generates two "Person" objects in the "Main" class with different values—"John Doe" and 30 for person1 and "Jane Doe" and 25 for person2—and uses the "printInfo" function to print out their respective information.

Output

Name: John Doe
Age: 30
Name: Jane Doe
Age: 25

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 provide developers with more control over how objects are instantiated within their program.
  • 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.

Example

public class MyClass {
    private static MyClass instance;
    private MyClass() {
        // private constructor
    }
    public static MyClass getInstance() {
        if (instance == null) {
            instance = new MyClass();
        }
        return instance;
    }
    public void showMessage() {
        System.out.println("Hello, World!");
    }
}

"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.
  • Along with being able to pass arguments among constructors, constructor chaining can be used to create aliases for a constructor or even allow the use of default values when needed.
  • By using constructor chaining, a programmer can easily utilize the full potential of Object-Oriented Programming 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();
}

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 different set of parameters than specified in its Superclass by calling 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.

Example

public 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);
    }
}
public 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();
    }
}

In this Java example, 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 for creating an exact replica of an existing object.
  • This type of constructor helps to reduce code redundancy and make programs more maintainable.
  • Copy Constructors are basically 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.

 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();
    }
}

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. In the "main" method, it 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

FAQs

1. What are constructors in Java?

Java constructors are unique methods used to initialize objects belonging to a class. They are called when an object is created and share the same name as the class.

2. Why is a constructor used?

When a new instance of an object is formed, constructors are used to initializing its member variables, set up the object's initial state, and carry out any other necessary setup duties.

3. How many constructors can be used in Java?

Java supports constructor overloading by enabling the use of several constructors, each of which might have a different set of parameters.

4. Can we overload a constructor?

In Java, constructors can be overloaded, which allows you to declare numerous constructors with unique parameter lists for a class.

5. Can a constructor be private?

In Java, a constructor can indeed be declared private. In design patterns like the Singleton pattern, private constructors are often utilized to limit class instantiation to within the class itself.

Summary

After learning about Java Constructors, the constructor in Java, constructor in Java example, use of constructor 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. 

Share
About Author
Shailendra Chauhan (Microsoft MVP, Founder & CEO at DotNetTricks)

Shailendra Chauhan is the Founder and CEO at ScholarHat by DotNetTricks which is a brand when it comes to e-Learning. He provides training and consultation over an array of technologies like Cloud, .NET, Angular, React, Node, Microservices, Containers and Mobile Apps development. He has been awarded Microsoft MVP 8th time in a row (2016-2023). He has changed many lives with his writings and unique training programs. He has a number of most sought-after books to his name which has helped job aspirants in cracking tough interviews with ease.
Accept cookies & close this