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 setIf 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
MediumCreate 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 setIf 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());
}
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Object Oriented Programming
1Fundamentals of OOP
External FilesIntroduction to OOPClasses vs ObjectsThe this KeywordMethodsFields (Attributes)Constructor MethodConstructor OverloadingRecap - Simple Calculator4Inheritance
Basic Inheritance (extends)The super KeywordMethod Overriding (@Override)Constructor ChainingThe Object ClassSingle & Multilevel InheritWhy No Multi Class InheritRecap - Employee Hierarchy7Special Methods & Object Class
toString() Methodequals() and hashCode()clone() MethodcompareTo() and ComparableComparator InterfaceRecap - Custom Sorting2Access Modifiers & Encapsulate
Access Levels OverviewGetter and Setter MethodsInformation HidingThe final KeywordRecap - Bank Account Manager5Polymorphism
Method Overloading BasicsMethod Overriding (Run-Time)Upcasting and DowncastingThe instanceof OperatorAbstract Classes and MethodsRecap - Shape Calculator8Advanced OOP Concepts
Composition vs InheritanceAggregation vs CompositionInner Nested & Anonymous ClassEnums and Enum MethodsRecords (Java 16+)Sealed Classes (Java 17+)3Class Props & Static Member
Instance vs Static VariablesStatic MethodsStatic BlocksConstants (static final)Recap - Counter & Utility6Interfaces & Abstract Classes
Introduction to InterfacesImplementing InterfacesMulti Interface ImplemenDefault & Static in InterfaceAbstract Classes vs InterfacesFunctional InterfacesRecap - Payment System