You can use the extends keyword to create a class that inherits fields and methods from another class.
The existing class is called the superclass. The new class is called the subclass.
In this example, you will create an Ebook class that extends a Book class. An ebook has a title and an author, just like a book, plus a file format.
Source code
public class InheritanceExample {
void main() {
Ebook ebook = new Ebook(
"Learning Java", "Alice", "PDF");
ebook.printDetails();
IO.println("File format: " + ebook.getFileFormat());
}
}
class Book {
private final String title;
private final String author;
Book(String title, String author) {
this.title = title;
this.author = author;
}
public void printDetails() {
IO.println("Title: " + title);
IO.println("Author: " + author);
}
}
class Ebook extends Book {
private final String fileFormat;
Ebook(String title, String author, String fileFormat) {
super(title, author);
this.fileFormat = fileFormat;
}
public String getFileFormat() {
return fileFormat;
}
}
Explanation
The Book class stores a title and an author. It also provides a printDetails() method to display those values.
The following declaration makes Ebook a subclass of Book:
class Ebook extends Book {
An Ebook inherits the accessible methods of Book, including its public printDetails() method. It also declares its own field, fileFormat.
Calling the superclass constructor
The Ebook constructor accepts values for both the book details and the file format:
Ebook(String title, String author, String fileFormat) {
super(title, author);
this.fileFormat = fileFormat;
}
The statement super(title, author) calls the Book constructor to initialize the title and author.
Constructors are not inherited. The subclass declares its own constructor and calls an appropriate superclass constructor.
Using an inherited method
After creating an Ebook, you can call:
ebook.printDetails();
Although Ebook does not declare printDetails(), it inherits that method from Book.
The method runs on the ebook object and prints the title and author initialized by the superclass constructor.
Accessing subclass data
The subclass provides a getter for its additional field:
public String getFileFormat() {
return fileFormat;
}
The calling code uses this method to read the ebook’s file format:
IO.println("File format: " + ebook.getFileFormat());
The superclass fields remain private. Code inside Ebook cannot access title or author directly; the Book class manages those fields.
Run the example
Compile and run the file:
javac InheritanceExample.java
java InheritanceExample
Output
Title: Learning Java
Author: Alice
File format: PDF
Use inheritance when the subclass represents a more specific kind of the superclass. In this example, an ebook is a book with an additional file format.
