Menu
Coddy logo textTech

Constructor Method

Part of the Object Oriented Programming section of Coddy's Java journey — lesson 7 of 87.

A constructor is a special method that runs automatically when you create an object with new. It has the same name as the class and no return type.

Basic constructor

public class Book {
    private String title;
    private String author;
    
    public Book(String title, String author) {
        this.title = title;
        this.author = author;
    }
}

Default constructor (no parameters)

public class Book {
    private String title;
    
    public Book() {
        this.title = "Unknown";
    }
}

The constructor initializes the object's state

Book book = new Book("1984", "Orwell");
// Constructor runs immediately, fields are set

If you don't write a constructor, Java provides a default empty one. Once you write any constructor, the default one is no longer provided automatically.

challenge icon

Challenge

Medium

Create a Book class with a constructor that initializes all fields:

  • Private fields: title, author (String), pages (int)
  • A constructor that takes all three values and assigns them using this
  • Getter methods for each field
  • A getSummary() method returning "<title> by <author> (<pages> pages)"

Cheat sheet

A constructor is a special method that runs automatically when you create an object with new. It has the same name as the class and no return type.

Basic constructor:

public class Book {
    private String title;
    private String author;
    
    public Book(String title, String author) {
        this.title = title;
        this.author = author;
    }
}

Default constructor (no parameters):

public class Book {
    private String title;
    
    public Book() {
        this.title = "Unknown";
    }
}

Using a constructor to create an object:

Book book = new Book("1984", "Orwell");
// Constructor runs immediately, fields are set

If you don't write a constructor, Java provides a default empty one. Once you write any constructor, the default one is no longer provided automatically.

Try it yourself

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String title = scanner.nextLine();
        String author = scanner.nextLine();
        int pages = Integer.parseInt(scanner.nextLine());
        
        Book book = new Book(title, author, pages);
        
        System.out.println("Title: " + book.getTitle());
        System.out.println("Author: " + book.getAuthor());
        System.out.println("Pages: " + book.getPages());
        System.out.println(book.getSummary());
    }
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Object Oriented Programming