Popular Searches
Popular Course Categories
Popular Courses

Working with Default and Parameterized Constructors

Working with Default and Parameterized Constructors

Object-Oriented Programming Fundamentals

Working with Default and Parameterized Constructors in Java

Course: Core Java Training

Topic: Working with Default and Parameterized Constructors

Course Link: Core Java Training Course

Demo Link: Register for a Course Demo

Website: JustAcademy


1. Introduction to Constructors in Java

A constructor in Java is a special class member used to initialize an object when it is created. It helps assign initial values to fields and ensures that an object starts with an appropriate state.

Whenever an object is created using the new keyword, a suitable constructor is invoked. Constructors are especially useful when working with classes that contain fields such as name, age, employee ID, price, or account balance.

Java commonly involves two important constructor concepts: default constructors and parameterized constructors. Understanding the difference between them helps developers initialize objects correctly and write reusable object-oriented programs.

For example, consider a Student class. A constructor can initialize a student's name and age when the object is created, rather than requiring separate assignments for every field afterward.

class Student {
    String name;
    int age;

    Student() {
        name = "Unknown";
        age = 18;
    }
}

In this example, the constructor initializes the fields whenever a Student object is created using the no-argument constructor.

2. Learning Objectives

After completing this topic, you will be able to:

  • Understand the purpose and role of constructors in Java.
  • Identify the characteristics and syntax of constructors.
  • Understand Java's compiler-provided default constructor.
  • Define and use no-argument constructors.
  • Create parameterized constructors to initialize objects with specific values.
  • Differentiate between default, no-argument, and parameterized constructors.
  • Use the this keyword inside constructors.
  • Understand constructor overloading and constructor chaining.
  • Apply constructors in practical Java programs.
  • Identify common constructor errors and follow best practices.

3. What Is a Constructor?

A constructor is a special member of a class that initializes an object. Its name must match the class name, and it does not declare a return type, not even void.

3.1 Main Characteristics of Constructors

  • A constructor has the same name as its class.
  • It does not have a return type.
  • It is invoked when an object is instantiated.
  • It can accept parameters or have no parameters.
  • A class can have multiple constructors with different parameter lists.
  • Constructors can initialize instance fields and perform necessary setup operations.
  • Constructors are not inherited by subclasses.
  • A constructor cannot be declared static, abstract, or final.

3.2 General Constructor Syntax

class ClassName {
    ClassName() {
        // Initialization statements
    }
}

Example:

class Car {
    String brand;

    Car() {
        brand = "Toyota";
    }
}

Here, Car() is a constructor because its name matches the class name and it has no return type.

4. Understanding the Default Constructor

In Java, a default constructor is the no-argument constructor automatically provided by the compiler when a class does not declare any constructor.

The compiler-provided default constructor allows an object to be created without passing arguments. It performs the normal constructor initialization process, including invoking the superclass's no-argument constructor, when accessible.

4.1 Example of a Compiler-Provided Default Constructor

class Student {
    String name;
    int age;
}

class Main {
    public static void main(String[] args) {
        Student s1 = new Student();

        System.out.println(s1.name);
        System.out.println(s1.age);
    }
}

Output:

null
0

Because the Student class does not declare any constructor, Java provides a default constructor. The String field receives the default value null, and the int field receives the default value 0.

Important: The compiler provides this constructor only when no constructor is explicitly declared in the class. If you define any constructor yourself, the compiler does not automatically add a default constructor.

5. Understanding a No-Argument Constructor

A no-argument constructor is a constructor that does not accept any parameters. Unlike the compiler-provided default constructor, a no-argument constructor can be explicitly written by the programmer.

It is commonly used to initialize fields with meaningful default values rather than relying on Java's default field values.

5.1 Example of an Explicit No-Argument Constructor

class Employee {
    String name;
    double salary;

    Employee() {
        name = "Not Assigned";
        salary = 25000;
    }

    void displayDetails() {
        System.out.println("Name: " + name);
        System.out.println("Salary: " + salary);
    }
}

class Main {
    public static void main(String[] args) {
        Employee emp = new Employee();
        emp.displayDetails();
    }
}

Output:

Name: Not Assigned
Salary: 25000.0

The constructor initializes the Employee object with predefined values. This allows the program to create a usable object without supplying information at the time of instantiation.

5.2 Benefits of No-Argument Constructors

  • Allow objects to be created without passing arguments.
  • Provide a convenient way to establish initial field values.
  • Support frameworks and libraries that expect no-argument constructors in certain situations.
  • Make it easier to create objects before their data is available.
  • Can establish a predictable initial state for an object.

6. Understanding Parameterized Constructors

A parameterized constructor accepts one or more parameters. These parameters allow the caller to supply values when creating an object.

Parameterized constructors are useful when different objects need different initial values. For example, each Student object can have its own name, roll number, and marks.

6.1 Syntax of a Parameterized Constructor

class ClassName {
    ClassName(dataType parameter1, dataType parameter2) {
        // Initialize fields using parameters
    }
}

6.2 Example of a Parameterized Constructor

class Student {
    String name;
    int age;

    Student(String studentName, int studentAge) {
        name = studentName;
        age = studentAge;
    }

    void displayDetails() {
        System.out.println("Name: " + name);
        System.out.println("Age: " + age);
    }
}

class Main {
    public static void main(String[] args) {
        Student s1 = new Student("Rahul", 20);
        Student s2 = new Student("Priya", 22);

        s1.displayDetails();
        s2.displayDetails();
    }
}

Output:

Name: Rahul
Age: 20
Name: Priya
Age: 22

In this example, the constructor accepts two parameters and uses them to initialize the object's fields. Each object receives its own values when it is created.

6.3 Why Use Parameterized Constructors?

  • Initialize fields with caller-provided values.
  • Create multiple objects with different data.
  • Reduce repeated field assignments after object creation.
  • Make object initialization easier to read and maintain.
  • Help establish valid object states from the beginning.

7. Difference Between Default and Parameterized Constructors

Feature Default Constructor Parameterized Constructor
Definition Compiler-provided constructor when no constructor is declared. A constructor declared with one or more parameters.
Parameters No parameters. Accepts one or more parameters.
Creation Automatically supplied by the compiler when eligible. Explicitly declared by the programmer.
Initialization Performs default initialization unless other initialization logic applies. Can initialize fields using supplied arguments.
Object creation Can be used with new ClassName(). Called with matching arguments.
Flexibility Provides a standard no-argument construction path. Allows different initial values for different objects.
Example Student() provided by the compiler. Student(String name, int age).

Note: A programmer-written no-argument constructor is not the same thing as a compiler-provided default constructor, even though both can be called without arguments.

8. Using the this Keyword in Constructors

The this keyword refers to the current object. It is often used in parameterized constructors when parameter names match field names.

8.1 Example

class Product {
    int productId;
    String productName;
    double price;

    Product(int productId, String productName, double price) {
        this.productId = productId;
        this.productName = productName;
        this.price = price;
    }

    void display() {
        System.out.println(productId);
        System.out.println(productName);
        System.out.println(price);
    }
}

class Main {
    public static void main(String[] args) {
        Product p = new Product(101, "Laptop", 55000);
        p.display();
    }
}

Output:

101
Laptop
55000.0

Here, this.productId refers to the field of the current object, while productId refers to the constructor parameter. This distinction makes the code easier to understand.

9. Constructor Overloading

Constructor overloading means defining multiple constructors in the same class with different parameter lists. The compiler selects the appropriate constructor based on the arguments supplied during object creation.

Overloaded constructors may differ in the number, types, or order of their parameters.

9.1 Example of Constructor Overloading

class Book {
    String title;
    double price;

    Book() {
        title = "Untitled";
        price = 0;
    }

    Book(String title) {
        this.title = title;
        price = 0;
    }

    Book(String title, double price) {
        this.title = title;
        this.price = price;
    }

    void display() {
        System.out.println(title + " - " + price);
    }
}

class Main {
    public static void main(String[] args) {
        Book b1 = new Book();
        Book b2 = new Book("Java Basics");
        Book b3 = new Book("Advanced Java", 750);

        b1.display();
        b2.display();
        b3.display();
    }
}

Output:

Untitled - 0.0
Java Basics - 0.0
Advanced Java - 750.0

This class offers three construction options. A caller can create a book with default values, supply a title, or supply both a title and a price.

10. Constructor Chaining Using this()

Constructor chaining allows one constructor to invoke another constructor in the same class using this(). It reduces duplicated initialization logic.

A call to this() must be the first statement in the constructor body in traditional Java constructor syntax. It must also match an available constructor parameter list.

10.1 Example

class Employee {
    String name;
    double salary;
    String department;

    Employee() {
        this("Unknown", 0, "General");
    }

    Employee(String name, double salary) {
        this(name, salary, "General");
    }

    Employee(String name, double salary, String department) {
        this.name = name;
        this.salary = salary;
        this.department = department;
    }

    void display() {
        System.out.println(name + " | " + salary
                + " | " + department);
    }
}

class Main {
    public static void main(String[] args) {
        Employee e1 = new Employee();
        Employee e2 = new Employee("Amit", 40000);
        Employee e3 = new Employee("Neha", 50000, "IT");

        e1.display();
        e2.display();
        e3.display();
    }
}

Output:

Unknown | 0.0 | General
Amit | 40000.0 | General
Neha | 50000.0 | IT

The no-argument constructor and the two-parameter constructor reuse the three-parameter constructor. This keeps the initialization rules in one place.

11. Using super() in Constructors

The super() call invokes a constructor of the immediate superclass. It is useful when a subclass must initialize the inherited portion of an object.

class Person {
    String name;

    Person(String name) {
        this.name = name;
    }
}

class Student extends Person {
    int rollNumber;

    Student(String name, int rollNumber) {
        super(name);
        this.rollNumber = rollNumber;
    }

    void display() {
        System.out.println(name);
        System.out.println(rollNumber);
    }
}

class Main {
    public static void main(String[] args) {
        Student s = new Student("Riya", 101);
        s.display();
    }
}

Output:

Riya
101

The super(name) statement calls the Person constructor to initialize the name field. The Student constructor then initializes rollNumber.

In Java's traditional constructor syntax, an explicit super() call must be the first statement unless a this() call is used instead. Modern Java also supports flexible constructor bodies under specific rules, but the traditional first-statement pattern remains widely used.

12. Constructor Initialization and Field Values

When an object is created, Java initializes its fields to default values before executing the constructor body. Field initializers and initialization blocks also participate in the class's initialization process.

For example, primitive fields receive values such as zero or false, and reference fields initially receive null unless their initialization changes those values.

class Account {
    String owner;
    double balance = 1000;

    Account(String owner) {
        this.owner = owner;
    }

    void display() {
        System.out.println(owner);
        System.out.println(balance);
    }
}

class Main {
    public static void main(String[] args) {
        Account account = new Account("Karan");
        account.display();
    }
}

Output:

Karan
1000.0

The balance field is initialized by its field initializer, while the constructor assigns the owner's name.

13. Validation Inside Parameterized Constructors

Constructors can validate arguments before storing them. This is useful when an object must not be created with invalid values.

class BankAccount {
    private String accountHolder;
    private double balance;

    BankAccount(String accountHolder, double balance) {
        if (accountHolder == null || accountHolder.isBlank()) {
            throw new IllegalArgumentException(
                    "Account holder cannot be blank");
        }

        if (balance < 0) {
            throw new IllegalArgumentException(
                    "Balance cannot be negative");
        }

        this.accountHolder = accountHolder;
        this.balance = balance;
    }

    void display() {
        System.out.println(accountHolder);
        System.out.println(balance);
    }
}

class Main {
    public static void main(String[] args) {
        BankAccount account = new BankAccount("Anita", 5000);
        account.display();
    }
}

Output:

Anita
5000.0

The constructor rejects invalid input by throwing an IllegalArgumentException. The isBlank() method is available in Java 11 and later.

14. Common Constructor Errors

Error Explanation Solution
Declaring a return type A constructor is accidentally written as void Student(), making it a method. Remove the return type.
Incorrect constructor name The name does not match the class name. Use the exact class name.
Expecting an automatic default constructor A custom constructor has already been declared. Declare a no-argument constructor explicitly if required.
Passing incorrect arguments No matching constructor is available for the supplied arguments. Check the parameter types, order, and number.
Incorrect use of this() The constructor call is not placed correctly or does not match another constructor. Place it first under traditional syntax and check the target signature.
Invalid initialization values Fields receive values that violate application rules. Validate parameters before assigning them.
Calling a superclass constructor incorrectly The superclass has no matching accessible constructor. Use a valid superclass constructor and supply required arguments.

15. Best Practices for Constructors

  • Use meaningful parameter names that clearly describe the expected values.
  • Initialize important fields during object creation whenever possible.
  • Use parameterized constructors when objects require specific initial data.
  • Provide a no-argument constructor only when it serves a practical purpose.
  • Remember that defining a constructor prevents the compiler from automatically supplying a default constructor.
  • Validate arguments to protect the object's state.
  • Use this.fieldName to distinguish fields from parameters when their names match.
  • Use constructor overloading to support legitimate initialization alternatives.
  • Use this() to reduce duplicated constructor logic.
  • Keep constructors focused on initialization rather than unrelated, lengthy business operations.
  • Use appropriate access modifiers to control whether objects can be constructed from other classes.
  • Write unit tests for important constructor scenarios, including invalid inputs.

16. Practical Exercise: Create a Mobile Class

Create a Mobile class with the following fields:

  • brand
  • model
  • price
  • storage

Requirements:

  1. Create a no-argument constructor that initializes the mobile with sensible default values.
  2. Create a parameterized constructor that accepts all four field values.
  3. Create a displayDetails() method to display the mobile information.
  4. Create two objects using the two different constructors.
  5. Test the program with different mobile details.

Sample Solution

class Mobile {
    String brand;
    String model;
    double price;
    int storage;

    Mobile() {
        this("Unknown", "Basic", 0, 32);
    }

    Mobile(String brand, String model, double price, int storage) {
        this.brand = brand;
        this.model = model;
        this.price = price;
        this.storage = storage;
    }

    void displayDetails() {
        System.out.println("Brand: " + brand);
        System.out.println("Model: " + model);
        System.out.println("Price: " + price);
        System.out.println("Storage: " + storage + " GB");
        System.out.println("------------------");
    }
}

class Main {
    public static void main(String[] args) {
        Mobile m1 = new Mobile();

        Mobile m2 = new Mobile(
                "Samsung", "Galaxy A", 25000, 128);

        m1.displayDetails();
        m2.displayDetails();
    }
}

Expected Output:

Brand: Unknown
Model: Basic
Price: 0.0
Storage: 32 GB
------------------
Brand: Samsung
Model: Galaxy A
Price: 25000.0
Storage: 128 GB
------------------

This exercise demonstrates how a no-argument constructor can provide default application-specific values while a parameterized constructor supports custom object initialization.

17. Interview Questions and Answers

Q1. What is a constructor in Java?

A constructor is a special class member used to initialize an object. It has the same name as its class and does not declare a return type.

Q2. What is a default constructor?

A default constructor is the no-argument constructor supplied by the compiler when a class does not explicitly declare any constructor.

Q3. What is a no-argument constructor?

A no-argument constructor is a constructor that accepts no parameters. It may be written by the programmer or supplied by the compiler when the default-constructor conditions are met.

Q4. What is a parameterized constructor?

A parameterized constructor accepts arguments that can be used to initialize an object's fields.

Q5. Does Java provide a default constructor if a parameterized constructor is declared?

No. If a class declares any constructor, the compiler does not automatically provide the default constructor. A no-argument constructor must be declared explicitly if needed.

Q6. Can constructors be overloaded?

Yes. A class can contain multiple constructors with different parameter lists.

Q7. Can a constructor be static?

No. Constructors cannot be declared static because they initialize objects rather than being class-level methods.

Q8. What is the purpose of this()?

The this() call invokes another constructor in the same class and helps reuse initialization logic.

Q9. What is the purpose of super()?

The super() call invokes a constructor of the immediate superclass to initialize the inherited portion of an object.

Q10. Can a constructor return a value?

No. A constructor does not declare a return type. It initializes an object rather than returning a value like an ordinary method.

Q11. Are constructors inherited?

No. Constructors are not inherited by subclasses, although a subclass constructor can invoke an accessible superclass constructor.

Q12. Can a constructor be private?

Yes. A private constructor restricts object construction from outside the declaring class. This technique is used in designs such as utility classes and some singleton implementations.

Q13. What happens when no constructor is declared?

The compiler provides a default no-argument constructor, subject to the superclass constructor requirements.

Q14. Why are parameterized constructors useful?

They allow objects to be initialized with specific values at creation time and reduce the need for repeated assignments after object creation.

18. Quick Revision Checklist

  • A constructor initializes an object during creation.
  • A constructor has the same name as the class.
  • A constructor does not have a return type.
  • The compiler provides a default constructor only when no constructor is declared.
  • A programmer can explicitly define a no-argument constructor.
  • A parameterized constructor accepts values from the caller.
  • The this keyword refers to the current object.
  • Constructor overloading provides different initialization options.
  • The this() call invokes another constructor in the same class.
  • The super() call invokes a superclass constructor.
  • Constructor validation helps prevent invalid object states.
  • Good constructor design improves readability, reliability, and maintainability.

19. Conclusion

Default and parameterized constructors are essential concepts in Core Java and object-oriented programming. The compiler-provided default constructor offers a no-argument construction path when a class does not declare any constructors, while an explicitly defined no-argument constructor lets developers establish their own initial values.

Parameterized constructors allow objects to receive specific data at creation time. Constructor overloading, the this() keyword, and the super() call provide additional flexibility for designing reusable classes and managing initialization.

By practicing constructors with Student, Employee, Product, BankAccount, and Mobile classes, learners can build a strong foundation for inheritance, encapsulation, polymorphism, and more advanced Java development.


Learn Core Java with JustAcademy

Explore structured Java training and continue practicing object-oriented programming concepts with hands-on examples.

Explore the Core Java Training Course

Register for a Course Demo

Visit the JustAcademy Website

whatsapp