How to implement inheritance in Java? [SOLVED]


JAVA

Author: Bashir Alam
Reviewer: Deepak Prasad

Inheritance is a mechanism in Java where a new class is created from an existing class. The new class is called the subclass or derived class, and the existing class is called the superclass or base class. Inheritance enables the subclass to reuse the code of the superclass and add its own functionality. In this short article, we will discuss how to implement inheritance in Java by solving various examples.

 

What is inheritance in Java?

Inheritance is a fundamental concept in object-oriented programming that allows a new class to be based on an existing class. The new class, called the subclass or derived class, inherits the properties and methods of the existing class, called the superclass or base class. In Java, inheritance is used to create new classes that are based on existing classes, thereby reusing code and reducing code duplication. The subclass can add its own properties and methods or override the methods of the superclass. Inheritance is an important concept for creating modular, maintainable, and extensible software.

The following is the simple syntax of the inheritance in Java programming language:

class Subclass extends Superclass {
  // code for subclass
}

In the above syntax, the keyword extends is used to inherit the properties and methods of the superclass.

 

Different Types of Inheritance in Java

Java supports the following types of inheritance:

  • Single Inheritance: In single inheritance, a class inherits from only one superclass. For example, class A can inherit from class B.
  • Multilevel Inheritance: In multilevel inheritance, a class inherits from a superclass, which itself inherits from another superclass. For example, class A can inherit from class B, which in turn can inherit from class C.
  • Hierarchical Inheritance: In hierarchical inheritance, more than one subclass inherits from the same superclass. For example, class A and class B can both inherit from class C.
  • Multiple Inheritance: Java doesn't support multiple inheritances directly. Multiple inheritances is a feature where a class can inherit from more than one superclass. However, Java supports multiple interface implementation, where a class can implement multiple interfaces.

 

Examples of inheritance in Java programming language

Now, we will go through various types of examples of inheritance in Java which will help us to understand how we can implement inheritance in Java.

 

Example-1: Single inheritance in Java

Let us first take the example of single inheritance in Java programming language.

class Shape {
    private String color;

    public Shape(String color) {
        this.color = color;
    }

    public String getColor() {
        return color;
    }

    public void setColor(String color) {
        this.color = color;
    }

    public void draw() {
        System.out.println("Drawing a shape");
    }
}

class Circle extends Shape {
    private double radius;

    public Circle(String color, double radius) {
        super(color);
        this.radius = radius;
    }

    public double getRadius() {
        return radius;
    }

    public void setRadius(double radius) {
        this.radius = radius;
    }

    public void draw() {
        System.out.println("Drawing a circle");
    }

    public double getArea() {
        return Math.PI * radius * radius;
    }
}

public class Main {
    public static void main(String[] args) {
        Circle circle = new Circle("red", 5.0);
        System.out.println("Color: " + circle.getColor());
        System.out.println("Radius: " + circle.getRadius());
        System.out.println("Area: " + circle.getArea());
        circle.draw();
    }
}

Output:

Color: red
Radius: 5.0
Area: 78.53981633974483
Drawing a circle

In this example, we have a Shape class that has a color property and a draw() method. We also have a Circle class that extends the Shape class and adds a radius property and a getArea() method. The Circle class overrides the draw() method of the Shape class to provide its own implementation.

In the Main class, we create an instance of the Circle class and call its methods. We can see that the Circle class inherits the color property and the draw() method from the Shape class, and also adds its own radius property and getArea() method.

 

Example-2: Multilevel inheritance in Java

Now, we will take an example of multilevel inheritance in Java.

class Animal {
    public void eat() {
        System.out.println("Animal is eating");
    }
}

class Dog extends Animal {
    public void bark() {
        System.out.println("Dog is barking");
    }
}

class GermanShepherd extends Dog {
    public void guard() {
        System.out.println("German Shepherd is guarding");
    }
}

public class Main {
    public static void main(String[] args) {
        GermanShepherd gs = new GermanShepherd();
        gs.eat();
        gs.bark();
        gs.guard();
    }
}

Output:

Animal is eating
Dog is barking
German Shepherd is guarding

In this example, we have an Animal class that has an eat() method. We also have a Dog class that extends the Animal class and adds a bark() method. Finally, we have a GermanShepherd class that extends the Dog class and adds a guard() method.

In the Main class, we create an instance of the GermanShepherd class and call its methods. We can see that the GermanShepherd class inherits the eat() method from the Animal class and the bark() method from the Dog class, and also adds its own guard() method.

 

Example-3: Hierarchical inheritance

Hierarchical inheritance is more complex than others. Let us first take an example and then explain how it works.

class Shape {
    private String color;

    public Shape(String color) {
        this.color = color;
    }

    public String getColor() {
        return color;
    }

    public void setColor(String color) {
        this.color = color;
    }

    public void draw() {
        System.out.println("Drawing a shape");
    }
}

class Circle extends Shape {
    private double radius;

    public Circle(String color, double radius) {
        super(color);
        this.radius = radius;
    }

    public double getRadius() {
        return radius;
    }

    public void setRadius(double radius) {
        this.radius = radius;
    }

    public void draw() {
        System.out.println("Drawing a circle");
    }

    public double getArea() {
        return Math.PI * radius * radius;
    }
}

class Square extends Shape {
    private double side;

    public Square(String color, double side) {
        super(color);
        this.side = side;
    }

    public double getSide() {
        return side;
    }

    public void setSide(double side) {
        this.side = side;
    }

    public void draw() {
        System.out.println("Drawing a square");
    }

    public double getArea() {
        return side * side;
    }
}

public class Main {
    public static void main(String[] args) {
        Circle circle = new Circle("red", 5.0);
        System.out.println("Color: " + circle.getColor());
        System.out.println("Radius: " + circle.getRadius());
        System.out.println("Area: " + circle.getArea());
        circle.draw();

        Square square = new Square("blue", 3.0);
        System.out.println("Color: " + square.getColor());
        System.out.println("Side: " + square.getSide());
        System.out.println("Area: " + square.getArea());
        square.draw();
    }
}

Output:

Color: red
Radius: 5.0
Area: 78.53981633974483
Drawing a circle
Color: blue
Side: 3.0
Area: 9.0
Drawing a square

In this example, we have a Shape class that has a color property and a draw() method. We also have a Circle class and a Square class, both of which extend the Shape class and add their own properties and methods. The Circle class has a radius property and a getArea() method, while the Square class has a side property and a getArea() method. Both classes override the draw() method of the Shape class to provide their own implementation.

In the Main class, we create an instance of the Circle class and the Square class and call their methods. We can see that both classes inherit the color property and the draw() method from the Shape class, and also add their own properties and methods.

 

Example-4: Multiple Inheritance

Multiple inheritance is the concept in which a class can inherit properties and methods from multiple superclasses. In Java, multiple inheritance is not directly supported, meaning a class cannot directly inherit from multiple classes at the same time. However, you can achieve a similar effect using interfaces, which allow a class to inherit from multiple interfaces.

Here's an example of multiple inheritance using interfaces in Java:

interface Animal {
    public void eat();
}

interface Mammal {
    public void run();
}

class Dog implements Animal, Mammal {
    public void eat() {
        System.out.println("Dog is eating");
    }

    public void run() {
        System.out.println("Dog is running");
    }
}

class Main {
    public static void main(String[] args) {
        Dog myDog = new Dog();
        myDog.eat(); // Output: Dog is eating
        myDog.run(); // Output: Dog is running
    }
}

In this example, we define two interfaces: Animal and Mammal. Both interfaces declare a method, eat() and run(), respectively.

Then, we define a class Dog that implements both Animal and Mammal interfaces. This allows the Dog class to inherit properties and methods from both interfaces.

In the Main class, we create an object of the Dog class and call its eat() and run() methods, which were inherited from the Animal and Mammal interfaces, respectively.

This is an example of how you can achieve a similar effect of multiple inheritance using interfaces in Java. However, note that there are limitations to this approach, and it's important to carefully design your class hierarchy to avoid complications and conflicts.

 

Summary

Inheritance is a fundamental concept in object-oriented programming that allows a class to inherit properties and behavior from another class. In Java, you can implement inheritance using the extends keyword. When you extend a class in Java, the subclass inherits all the properties and methods of the superclass, including its fields and methods. To create an object of the subclass, you can call both the inherited methods and the subclass-specific methods. You can define additional methods or fields in the subclass, but you need to call the superclass constructor using the super() method in the subclass constructor.

 

Further reading

Java Inheritance

 

Bashir Alam

Bashir Alam

He is a Computer Science graduate from the University of Central Asia, currently employed as a full-time Machine Learning Engineer at uExel. His expertise lies in Python, Java, Machine Learning, OCR, text extraction, data preprocessing, and predictive models. You can connect with him on his LinkedIn profile.

Can't find what you're searching for? Let us assist you.

Enter your query below, and we'll provide instant results tailored to your needs.

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can send mail to admin@golinuxcloud.com

Thank You for your support!!

Leave a Comment