Java ProgramsOOPConstructors

Constructors in Java

beginner·  OOP  ·  Constructors

Problem

A constructor is a special block of code, matching the class's own name, that runs automatically once when an object is created, giving it a chance to set up its initial fields.

Define a Book class whose constructor sets its title and author as soon as an object is created.

Input
title = "1984", author = "George Orwell"
Output
Book: 1984 by George Orwell

Java Program

Java
class Book { String title; String author; Book(String title, String author) { this.title = title; this.author = author; } } public class Constructors { public static void main(String[] args) { Book book = new Book("1984", "George Orwell"); // constructor runs as part of new System.out.println("Book: " + book.title + " by " + book.author); } }

Output

Book: 1984 by George Orwell

Core Logic

Writing the field-setting logic once inside a constructor, instead of assigning fields manually after every new, guarantees every Book object starts out fully initialized.

How It Works
  1. 1Book(String title, String author) is the constructor — it shares the class's exact name and has no return type, not even void.
  2. 2Its body assigns both parameters straight to the object's fields, title and author.
  3. 3new Book("1984", "George Orwell") both allocates the object and immediately runs this constructor on it, in one step.
  4. 4By the time the new expression finishes, the returned Book object already has both fields set.
Calling new Book("1984", "George Orwell") runs the constructor once, producing a Book object printed as "Book: 1984 by George Orwell".
💡

Key Point: A constructor runs automatically as part of new — there's no separate step where an object exists but hasn't been initialized yet, as long as the constructor itself sets every field it's responsible for.

Key Concepts

constructorobject initializationnew keyword

Related Programs