Inheritance in Java: Understanding Object-Oriented Programming

TechDyer

In the broad realm of programming, Inheritance in Java is a fundamental component of object-oriented programming (OOP), particularly in Java. Classes can take advantage of this strong mechanism to inherit frequently used methods and attributes from other classes. In addition to encouraging code reuse, inheritance makes it easier to establish relationships and hierarchies between classes.

What Is Inheritance in Java?

One of the concepts of object-oriented programming in Java is inheritance. Data members and properties can be acquired from one class to another through inheritance.

Why Do We Need Java Inheritance?

  • Code Reusability: All subclasses share the same code written in the superclass. The parent class code is directly usable by child classes.
  • Method Overriding: The only way to achieve method overriding is through inheritance. It’s one of the methods Java uses to implement Run Time Polymorphism.
  • Abstraction: Through inheritance, we can achieve the abstract concept where we do not have to provide all the details. Abstraction merely presents the user with the functionality.

Important Terminologies Used in Java Inheritance

Class: A class is a collection of objects that have similar traits, behaviors, and properties. Class is not a thing in the actual world. It serves only as a model, blueprint, or prototype that is used to create other objects.

Super Class/Parent Class: A superclass, also referred to as a base class or parent class, is a class whose features are inherited.

Sub Class/Child Class: A subclass (also called a derived class, extended class, or child class) is the class that inherits the other class. In addition to the fields and methods of the superclass, the subclass can also add its fields and methods.

Reusability: The idea of “reusability,” or the ability to derive a new class from an existing one when we need to create a new one and the existing class contains some of the code we want, is supported by inheritance. 

See also  What is Rest API in Java? A Beginner's Guide

How to Use Inheritance in Java?

Java uses the extends keyword to support inheritance. If you use the extends keyword, it means you are descended from a class that already exists. Stated differently, “extends” denotes greater functionality.

Syntax: 

class DerivedClass extends BaseClass  

{  

   //methods and fields  

}  

Inheritance in Java Example 1:
Class Bicycle is the base class, class Mountainbike is a derived class that extends the Bicycle class, and class Test is the driver class that launches the program in the inheritance example below. 

// Java program to illustrate the

// concept of inheritance

// base class

class Bicycle {

   //The Bicycle class comprises two fields.

    public int gear;

    public int speed;

    // The constructor for the Bicycle class is one.

    public Bicycle(int gear, int speed)

    {

        this.gear = gear;

        this.speed = speed;

    }

    // There are three ways in the Bicycle class.

    public void applyBrake(int decrement)

    {

        speed -= decrement;

    }

    public void speedUp(int increment)

    {

        speed += increment;

    }

    // toString() method to print the bicycle’s information

    public String toString()

    {

        return (“No of gears are ” + gear + “\n”

                + “speed of bicycle is ” + speed);

    }

}

// derived class

class MountainBike extends Bicycle {

    // the MountainBike subclass adds one more field

    public int seatHeight;

    // the MountainBike subclass has one constructor

    public MountainBike(int gear, int speed,

                        int startHeight)

    {

        // invoking base-class(Bicycle) constructor

        super(gear, speed);

        seatHeight = startHeight;

    }

    // the MountainBike subclass adds one more method

    public void setHeight(int newValue)

    {

        seatHeight = newValue;

    }

    // overriding toString() method

    // of Bicycle to print more info

    @Override public String toString()

    {

        return (super.toString() + “\nseat height is “

                + seatHeight);

    }

}

// driver class

public class Test {

    public static void main(String args[])

    {

        MountainBike(3, 100, 25) mb = new MountainBike;

        System.out.println(mb.toString());

    }

}

Output: 

No of gears are 3

speed of the bicycle is 100

seat height is 25

Example 2: Class Employee is the base class, class Engineer is a derived class that extends the Employee class, and class Test is the driver class that launches the application in the inheritance example below.

See also  Flutter vs React Native: Decoding Mobile Development

// Java Program to illustrate Inheritance (concise)

import java.io.*;

// Base or Super Class

class Employee {

    int salary = 60000;

}

// Inherited or Sub Class

class Engineer extends Employee {

    int benefits = 10000;

}

// Driver Class

class Gfg {

    public static void main(String args[])

    {

        Engineer E1 = new Engineer();

        System.out.println(“Salary: ” + E1.salary

                           + “\nBenefits: ” + E1.benefits);

    }

}

Java Inheritance Types

Single Inheritance: Subclasses inherit one superclass’s features when there is a single inheritance. Class A in the illustration below acts as the base class from which class B is derived.

Single Inheritance

// Java program to illustrate the

// concept of single inheritance

import java.io.*;

import java. lang.*;

import java. util.*;

// Parent class

class One {

    public void print_geek()

    {

        System.out.println(“Geeks”);

    }

}

class Two extends One {

    public void print_for() { System.out.println(“for”); }

}

// Driver class

public class Main {

      // Main function

    public static void main(String[] args)

    {

        Two g = new Two();

        g.print_geek();

        g.print_for();

        g.print_geek();

    }

}

Multilevel Inheritance: A derived class that participates in multilevel inheritance will inherit a base class, and it will also serve as the base class for other classes. The derived class B in the picture below uses class A as a base class, and class C uses class B as a base class. 

Multilevel Inheritance

// Java program to illustrate the

// concept of Multilevel inheritance

import java.io.*;

import java. lang.*;

import java. util.*;

class One {

    public void print_geek()

    {

        System.out.println(“Geeks”);

    }

}

class Two extends One {

    public void print_for() { System.out.println(“for”); }

}

class Three extends Two {

    public void print_geek()

    {

        System.out.println(“Geeks”);

    }

}

// Drived class

public class Main {

    public static void main(String[] args)

    {

        Three g = new Three();

        g.print_geek();

        g.print_for();

        g.print_geek();

    }

}

Hierarchical Inheritance: One class acts as a superclass (base class) for multiple subclasses under hierarchical inheritance. Class A is the base class in the illustration below, from which classes B, C, and D are derived.

Hierarchical Inheritance

// Java program to illustrate the

// concept of Hierarchical  inheritance

class A {

    public void print_A() { System.out.println(“Class A”); }

}

class B extends A {

    public void print_B() { System.out.println(“Class B”); }

}

class C extends A {

    public void print_C() { “Class C”); } System.out.println

}

class D extends A {

See also  How to Make a Quiz in JavaScript?

    public void print_D() { System.out.println(“Class D”); }

}

// Driver Class

public class Test {

    public static void main(String[] args)

    {

        B obj_B = new B();

        obj_B.print_A();

        obj_B.print_B();

        C obj_C = new C();

        obj_C.print_A();

        obj_C.print_C();

        D obj_D = new D();

        obj_D.print_A();

        obj_D.print_D();

    }

}

Multiple Inheritance: One class can have more than one superclass and inherit characteristics from each of its parent classes when there are multiple inheritances. Note that Java does not allow for more than one class inheritance. Multiple inheritance in Java is only possible with Interfaces. Class C in the illustration below is derived from interfaces A and B.

Multiple Inheritance

// Java program to illustrate the

// concept of Multiple inheritance

import java.io.*;

import java. lang.*;

import java. util.*;

interface One {

    public void print_geek();

}

interface Two {

    public void print_for();

}

interface Three extends One, Two {

    public void print_geek();

}

class Child implements Three {

    @Override public void print_geek()

    {

        System.out.println(“Geeks”);

    }

    public void print_for() { System.out.println(“for”); }

}

// Drived class

public class Main {

    public static void main(String[] args)

    {

        Child c = new Child();

        c.print_geek();

        c.print_for();

        c.print_geek();

    }

}

Advantages Of Inheritance in Java

Code Reusability: The amount of code that needs to be written is decreased and code reused thanks to inheritance. Code duplication can be minimized by the subclass by reusing the superclass’s methods and properties.

Abstraction: Abstract classes that define a common interface for a collection of related classes can be created thanks to inheritance. This encourages encapsulation and abstraction, which facilitates code maintenance and extension.

Class Hierarchy: A class hierarchy can be created through inheritance and used to model real-world objects and their relationships.

Polymorphism: The capacity of an object to assume different forms is known as polymorphism, and it is made possible by inheritance. Because they can override the superclass’s methods, subclasses can alter their behavior in various ways.

Conclusion

Programming in object-oriented Java requires a basic understanding of inheritance. It promotes code reuse and a hierarchical structure by allowing classes to inherit fields and methods from other classes. Gaining expertise in inheritance enables developers to create Java applications that are scalable, modular, and easily maintained.

Read more

Share This Article
Follow:
I'm a tech enthusiast and content writer at TechDyer.com. With a passion for simplifying complex tech concepts, delivers engaging content to readers. Follow for insightful updates on the latest in technology.
Leave a comment

Leave a Reply

Your email address will not be published. Required fields are marked *