Extend Two Classes in Java

Mohammad Irfan Oct 12, 2021 Jul 10, 2021
  1. Extend a Class in Java
  2. Extend Two Classes in Java
  3. Extend Two Interfaces in Java
Extend Two Classes in Java

This tutorial introduces how to extend two or more classes in Java. We also included some example codes to help you understand the topic.

Inheritance is a Java OOPs feature that allows extending a class to another class to access properties of a class. Java allows extending class to any class, but it has a limit. It means a class can extend only a single class at a time. Extending more than one class will lead to code execution failure.

When a class extends a class, then it is called single inheritance. If a class extends more than one class, it is called multi-inheritance, which is not allowed in Java.

Let’s see some examples and understand the complete concept.

Extend a Class in Java

Java does not allow multiple inheritances. In this example, we created two classes. A class extends to another and executes fine; this means that Java allows the extension of a single class. Still, what if we extend two classes? We will see this in the following example below.

class Run{
    int speed;
    void showSpeed() {
        System.out.println("Current Speed : "+speed);
    
}
public class SimpleTesting extends Run{
    public static void main(String[] args) {
        SimpleTesting run = new SimpleTesting();
        run.showSpeed();
        run.speed = 20;
        run.showSpeed();
    }
}
}

Output:

Current Speed : 0
Current Speed : 20

Extend Two Classes in Java

In this example method, a class extends two classes, which implies multiple inheritances. Java does not allow this process so the code does not execute and gives a compile time error. See the example below.

class Run{
    int speed;
    void showSpeed() {
        System.out.println("Current Speed : "+speed);
    }
}
class Car{
    String color;
    int topSpeed;
}
public class SimpleTesting extends Run, Car{
    public static void main(String[] args) {
        SimpleTesting run = new SimpleTesting();
        run.showSpeed();
        run.speed = 20;
        run.showSpeed();
    }
}

Output:

error

Extend Two Interfaces in Java

Two classes are not allowed, but a class can extend two interfaces in Java. This language allows extending two or more interfaces in a class. This code executes smoothly without any error. So, if you want to extend multiple inheritances, it would be better to use the interface. See the example below.

interface Run{
    int speed = 10;
    static void showSpeed() {
        System.out.println("Current Speed : "+speed);
    }
}

interface Car{
    String color = "Red";
    int topSpeed = 100;
}

public class Main implements Run, Car{
    public static void main(String[] args) {
        Main run = new Main();
        Run.showSpeed();
        System.out.println("Top Speed "+Car.topSpeed);
    }
}

Output:

Current Speed : 10
Top Speed 100

Related Article - Java Class