How do I extend a class in Java?

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.

How do I extend classes in Java?

Inheritance is one of object-oriented programming concepts. This concept allows classes to inherit commonly used state and behavior from other classes. Inheritance is the way to put commonly used states and behaviors into one class and reuse it.

The class that inherits all the attributes from other class is called as sub class. While, the class that inherited is called as superclass. You can use the extends keyword in class definition to inherit from other classes.

When you apply the final keyword to the class declaration you will make the class final, a final class cannot be extended by other class.

For example below we have, a Truck class and a Sedan that derived from a Car class.

package org.kodejava.basic;

public class CarDemo {
    public static void main(String[] args) {
        Car car = new Car();
        car.setBrand("Honda");
        System.out.println("Brand = " + car.getBrand());

        // The setBrand() and getBrand() is inherited from the Car
        // class.
        Truck truck = new Truck();
        truck.setBrand("Ford");
        System.out.println("Brand = " + truck.getBrand());
        int loadCapacity = truck.getLoadCapacity();

        // The setBrand(), getBrand() and setNumberOfSeat methods
        // are is inherited from the Car class.
        Sedan sedan = new Sedan();
        sedan.setBrand("Hyundai");
        System.out.println("Brand = " + sedan.getBrand());
        sedan.setNumberOfSeat(2);
        int gearType = sedan.getGearType();
    }
}

Here the definition of the Car, the Truck and the Sedan classes.

package org.kodejava.basic;

public class Car {
    private String type;
    private String brand;
    private String model;
    private int numberOfSeat;

    public Car() {
    }

    public Car(String type, String brand, String model) {
        this.type = type;
        this.brand = brand;
        this.model = model;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public String getBrand() {
        return brand;
    }

    public void setBrand(String brand) {
        this.brand = brand;
    }

    public String getModel() {
        return model;
    }

    public void setModel(String model) {
        this.model = model;
    }

    public int getNumberOfSeat() {
        return numberOfSeat;
    }

    public void setNumberOfSeat(int numberOfSeat) {
        this.numberOfSeat = numberOfSeat;
    }

    public String getCarInfo() {
        return "Type: " + type
                + "; Brand: " + brand
                + "; Model: " + model;
    }
}
package org.kodejava.basic;

public class Truck extends Car {
private int loadCapacity;

    public Truck() {
    }

    public Truck(String type, String brand, String model) {
        super(type, brand, model);
    }

    public int getLoadCapacity() {
        return loadCapacity;
    }

    public void setLoadCapacity(int loadCapacity) {
        this.loadCapacity = loadCapacity;
    }

    @Override
    public String getCarInfo() {
        return "Type: " + getType()
                + "; Brand: " + getBrand()
                + "; Model: " + getModel()
                + "; Load capacity: " + getLoadCapacity();
    }
}
package org.kodejava.basic;

public class Sedan extends Car {
    private int gearType;

    public Sedan() {
    }

    public int getGearType() {
        return gearType;
    }

    public void setGearType(int gearType) {
        this.gearType = gearType;
    }
}

How do I create a thread by extending Thread class?

There are two ways that we can use tho create a thread. First is by extending the java.lang.Thread class and the second way is by creating a class that implements the java.lang.Runnable interface. See How do I create a thread by implementing Runnable interface?

In this example we’ll extend the Thread class. To run a code in a thread we need to provide the run() method in our class. Let’s see the code below.

package org.kodejava.lang;

public class NumberPrinter extends Thread {
    private final String threadName;
    private final int delay;

    public NumberPrinter(String threadName, int delay) {
        this.threadName = threadName;
        this.delay = delay;
    }

    // The run() method will be invoked when the thread is started.
    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
            System.out.println("Thread [" + threadName + "] = " + i);

            try {
                Thread.sleep(delay);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        NumberPrinter printerA = new NumberPrinter("A", 1000);
        NumberPrinter printerB = new NumberPrinter("B", 750);

        printerA.start();
        printerB.start();
    }
}

The example result of our code is:

Thread [B] = 0
Thread [A] = 0
Thread [B] = 1
Thread [A] = 1
Thread [B] = 2
Thread [A] = 2
Thread [B] = 3
Thread [B] = 4
Thread [A] = 3
Thread [B] = 5
Thread [A] = 4
Thread [B] = 6
Thread [A] = 5
Thread [B] = 7
Thread [B] = 8
Thread [A] = 6
Thread [B] = 9
Thread [A] = 7
Thread [A] = 8
Thread [A] = 9