Skip to content

← Back to Overview

Java Program - Using Constructors

Concept Explanation

What is it?

A constructor is a special block of code similar to a method that is called when an instance of an object is created. Its primary purpose is to initialize the object's state.


Implementations

class Book {
    String title;
    String author;
    double price;

    // 1. Default Constructor (No arguments)
    Book() {
        title = "Unknown Title";
        author = "Unknown Author";
        price = 0.0;
    }

    // 2. Parameterized Constructor
    Book(String t, String a, double p) {
        title = t;
        author = a;
        price = p;
    }

    void displayInfo() {
        System.out.println("Title:  " + title);
        System.out.println("Author: " + author);
        System.out.println("Price:  $" + price);
        System.out.println("-----------------");
    }
}

public class ConstructorDemo {
    public static void main(String[] args) {
        // Calls Default Constructor
        Book b1 = new Book();
        b1.displayInfo();

        // Calls Parameterized Constructor
        Book b2 = new Book("The Alchemist", "Paulo Coelho", 15.99);
        b2.displayInfo();
    }
}

Explanation

  • Name: The constructor name must match the class name exactly.
  • Return Type: Constructors have no return type, not even void.
  • Overloading: You can have multiple constructors with different parameter lists (Constructor Overloading).

Interview Tips

  • Explain the difference between this() (calling another constructor) and super() (calling parent constructor).
  • What happens if you don't define any constructor? (Java provides a default one).

"Construction is the art of making a whole out of many parts." - Anonymous