Construction and Initialization

A constructor runs automatically at new and guarantees every object is born valid; define one with parameters and the compiler's free no-arg constructor quietly disappears.

10 min read · 10 cards · 2 checks

Read in: English · हिन्दी · ગુજરાતી


Theory

The book that was born broken

A new intern adds 20 books to BookBridge. On book 14 he sets the title, gets distracted, and never sets copies.

The object exists. Its copies field holds the default, 0. Weeks later a student tries to borrow it, issue() says no stock, and the one physical copy sits on the shelf unissued for a semester.

Nobody wrote a wrong value; someone merely forgot. The fix is to make forgetting impossible: no Book gets created without stating its facts.

Theory

The admission desk

A college does not let a student wander in and fill the form "whenever". Admission happens at a desk: name and course are taken at entry, or there is no admission.

A constructor is that desk for objects. It runs automatically at the moment of new, receives the facts as parameters, and only then hands over the object. Nothing enters the system half-registered.

Theory

Constructor, formally

A constructor is a special member that initialises a new object. Rules the exam checks:

  • its name is exactly the class name
  • it has no return type, not even void
  • it runs automatically when new executes; you never call it like a method
  • it can be overloaded: several constructors with different parameter lists

Book(String t, int c) { title = t; copies = c; }

Now new Book("Let Us C", 5) builds a complete book in one move.

Practical

Born complete, 2 ways

class Book {
    String title;
    int copies;

    Book(String t, int c) {     // parameterized constructor
        title = t;
        copies = c;
    }

    Book() {                    // no-arg constructor, written by US
        title = "Untitled";
        copies = 1;
    }
}

public class BookBridge {
    public static void main(String[] args) {
        Book b1 = new Book("Let Us C", 5);
        Book b2 = new Book();   // works because we wrote Book()
        System.out.println(b1.title + " | " + b1.copies);
        System.out.println(b2.title + " | " + b2.copies);
    }
}

Theory

The vanishing default constructor

Where did new Book() work from, back when Book had no constructor at all? The compiler supplied a default constructor: invisible, no arguments, fields left at their defaults.

The catch: that gift exists only while you define no constructor of your own. The moment you write Book(String t, int c), the free one vanishes. Any old new Book() in the program instantly becomes a compile error, unless you also write a no-arg constructor yourself, as the listing does.

Quiz

class Book { Book(String t) { title = t; } } Elsewhere someone writes: new Book(); What happens?

  1. Compile error: no matching constructor exists anymore
  2. It works; the compiler's default constructor is always available
  3. It works; fields just keep their default values
  4. Runtime exception when the missing constructor is first called
Show the answer

Compile error: no matching constructor exists anymore

Defining the String constructor removed the compiler's free no-arg one, so new Book() has nothing to match and compilation fails. Options B and C describe the world BEFORE any constructor was defined; that world ends with your first constructor. Option D is impossible: constructor matching is settled entirely at compile time. This vanishing-default rule is the most-asked constructor question in this paper.

Think first

The imposter constructor

A student writes: void Book() { title = "X"; } inside class Book, and is confused why new Book() never prints his debug line. Before tapping: what did he actually create?

Show the answer

An ordinary method that happens to be named Book. The moment a return type appears (even void), it is not a constructor, so new Book() never calls it; it quietly uses a constructor instead. His method would only run if someone wrote b.Book() explicitly, which nobody does. Exam rule: class name + NO return type = constructor; anything else is just a method.

Watch out

And the destructor?

BCA304 reflex: after the constructor lesson comes the destructor lesson. Not in Java. There are no destructors; the garbage collector reclaims unreachable objects (the locked-drawer trade from the comparison lesson).

If a comparison question asks, write: C++ pairs constructors with destructors for manual cleanup; Java pairs constructors with automatic garbage collection. Do not invent a Java destructor syntax; there is none to write.

Theory

One loose thread

Look at our constructor's parameters: Book(String t, int c). Why the cryptic t and c? Because naming them title and copies, the natural choice, creates a name clash with the fields, and solving that clash properly needs the this keyword. That is exactly the next lesson, where BookBridge's Person family also starts calling parent constructors with super. The admission desk is about to get a hierarchy.

Summary

Key takeaways

  • A constructor initialises the object at new: class name, no return type, never called manually.
  • Parameterized constructors make incomplete objects impossible: the facts arrive at birth.
  • The compiler's default constructor exists only while you define no constructor; your first one removes it.
  • Constructors overload: several parameter lists, one class name.
  • void Book() is a method, not a constructor: any return type disqualifies it.
  • Java has constructors but no destructors; garbage collection handles the other end of life.
  • Memory hook: no admission without the desk.

Study this properly

This page is the lesson to read. In Gri-Learn the same topic is a graded deck: the self-checks are scored and your weak topics are tracked. Free to start.

Start this topic

Already have an account? Sign in

More from Classes and Objects

Gri-Learn · syllabus-mapped B.C.A. lessons in English, Hindi and Gujarati

Construction and Initialization · Java Programming Language · Gri-Learn