0% found this document useful (0 votes)
31 views20 pages

Understanding Inheritance in Java

Inheritance in Java allows one class to inherit features from another class. The class whose features are inherited is called the superclass, while the class that inherits is called the subclass. The subclass inherits all fields and methods from the superclass and can add its own fields and methods. The keyword "extends" is used to inherit from a superclass. Inheritance supports code reusability and is an important pillar of object-oriented programming in Java.

Uploaded by

Saffa Ibrahim
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
31 views20 pages

Understanding Inheritance in Java

Inheritance in Java allows one class to inherit features from another class. The class whose features are inherited is called the superclass, while the class that inherits is called the subclass. The subclass inherits all fields and methods from the superclass and can add its own fields and methods. The keyword "extends" is used to inherit from a superclass. Inheritance supports code reusability and is an important pillar of object-oriented programming in Java.

Uploaded by

Saffa Ibrahim
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Inheritance in Java

 Difficulty Level : Easy


 Last Updated : 28 Jun, 2021
Inheritance is an important pillar of OOP(Object-Oriented Programming). It is the
mechanism in java by which one class is allowed to inherit the features(fields and
methods) of another class. 
Important terminology: 
 Super Class: The class whose features are inherited is known as superclass(or
a base class or a parent class).
 Sub Class: The class that inherits the other class is known as a subclass(or a
derived class, extended class, or child class). The subclass can add its own fields
and methods in addition to the superclass fields and methods.
 Reusability: Inheritance supports the concept of “reusability”, i.e. when we
want to create a new class and there is already a class that includes some of the
code that we want, we can derive our new class from the existing class. By doing
this, we are reusing the fields and methods of the existing class.
How to use inheritance in Java
The keyword used for inheritance is extends. 
Syntax : 

class derived-class extends base-class


{
//methods and fields
}
Example: In the below example of inheritance, class Bicycle is a base class, class
MountainBike is a derived class that extends Bicycle class and class Test is a driver
class to run program. 
Java

// Java program to illustrate the

// concept of inheritance

// base class
class Bicycle {

    // the Bicycle class has two fields

    public int gear;

    public int speed;

    // the Bicycle class has one constructor

    public Bicycle(int gear, int speed)

    {

        [Link] = gear;

        [Link] = speed;

    }

    // the Bicycle class has three methods

    public void applyBrake(int decrement)

    {

        speed -= decrement;

    }

 
    public void speedUp(int increment)

    {

        speed += increment;

    }

    // toString() method to print info of Bicycle

    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 ([Link]() + "\nseat height is "

                + seatHeight);

    }

// driver class

public class Test {

    public static void main(String args[])

    {

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

        [Link]([Link]());

    }

Output
No of gears are 3
speed of bicycle is 100
seat height is 25
In the above program, when an object of MountainBike class is created, a copy of all
methods and fields of the superclass acquire memory in this object. That is why by
using the object of the subclass we can also access the members of a superclass. 

Please note that during inheritance only the object of the subclass is created, not the
superclass. For more, refer Java Object Creation of Inherited Class . 
Illustrative image of the program: 
 

In practice, inheritance and polymorphism are used together in java to achieve fast


performance and readability of code.
Types of Inheritance in Java

Below are the different types of inheritance which are supported by Java. 
1. Single Inheritance: In single inheritance, subclasses inherit the features of one
superclass. In the image below, class A serves as a base class for the derived class
B.
Java

// Java program to illustrate the


// concept of single inheritance

import [Link].*;

import [Link].*;

import [Link].*;

class one {

    public void print_geek()

    {

        [Link]("Geeks");

    }

class two extends one {

    public void print_for() { [Link]("for"); }

// Driver class

public class Main {

    public static void main(String[] args)


    {

        two g = new two();

        g.print_geek();

        g.print_for();

        g.print_geek();

    }

Output
Geeks
for
Geeks

2. Multilevel Inheritance: In Multilevel Inheritance, a derived class will be inheriting a


base class and as well as the derived class also act as the base class to other class.
In the below image, class A serves as a base class for the derived class B, which in
turn serves as a base class for the derived class C. In Java, a class cannot directly
access the grandparent’s members.
Java
// Java program to illustrate the

// concept of Multilevel inheritance

import [Link].*;

import [Link].*;

import [Link].*;

class one {

    public void print_geek()

    {

        [Link]("Geeks");

    }

class two extends one {

    public void print_for() { [Link]("for"); }

class three extends two {


    public void print_geek()

    {

        [Link]("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();

    }

Output
Geeks
for
Geeks
3. Hierarchical Inheritance: In Hierarchical Inheritance, one class serves as a
superclass (base class) for more than one subclass. In the below image, class A
serves as a base class for the derived class B, C and D.
Java

// Java program to illustrate the

// concept of Hierarchical  inheritance

class A {

    public void print_A() { [Link]("Class A"); }

class B extends A {
    public void print_B() { [Link]("Class B"); }

class C extends A {

    public void print_C() { [Link]("Class C"); }

class D extends A {

    public void print_D() { [Link]("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();

    }

Output
Class A
Class B
Class A
Class C
Class A
Class D
Hierarchical Inheritance

4. Multiple Inheritance (Through Interfaces): In Multiple inheritances, one class can


have more than one superclass and inherit features from all parent classes. Please
note that Java does not support multiple inheritances with classes. In java, we can
achieve multiple inheritances only through Interfaces. In the image below, Class C is
derived from interface A and B.
Java

// Java program to illustrate the

// concept of Multiple inheritance

import [Link].*;

import [Link].*;

import [Link].*;

 
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()

    {

        [Link]("Geeks");

    }

    public void print_for() { [Link]("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();

    }

Output
Geeks
for
Geeks
5. Hybrid Inheritance(Through Interfaces): It is a mix of two or more of the above
types of inheritance. Since java doesn’t support multiple inheritances with classes,
hybrid inheritance is also not possible with classes. In java, we can achieve hybrid
inheritance only through Interfaces.
 
Important facts about inheritance in Java 
 Default superclass: Except Object class, which has no superclass, every class
has one and only one direct superclass (single inheritance). In the absence of any
other explicit superclass, every class is implicitly a subclass of the Object class.
 Superclass can only be one: A superclass can have any number of
subclasses. But a subclass can have only one superclass. This is because Java
does not support multiple inheritances with classes. Although with interfaces,
multiple inheritances are supported by java.
 Inheriting Constructors: A subclass inherits all the members (fields, methods,
and nested classes) from its superclass. Constructors are not members, so they
are not inherited by subclasses, but the constructor of the superclass can be
invoked from the subclass.
 Private member inheritance: A subclass does not inherit the private members
of its parent class. However, if the superclass has public or protected methods(like
getters and setters) for accessing its private fields, these can also be used by the
subclass.
Java IS-A type of Relationship.
IS-A is a way of saying: This object is a type of that object. Let us see how the extends
keyword is used to achieve inheritance.
Java

public class SolarSystem {

public class Earth extends SolarSystem {

public class Mars extends SolarSystem {

public class Moon extends Earth {

Now, based on the above example, in Object-Oriented terms, the following are true:-
1. SolarSystem the superclass of Earth class.
2. SolarSystem the superclass of Mars class.
3. Earth and Mars are subclasses of SolarSystem class.
4. Moon is the subclass of both Earth and SolarSystem classes.
Java

class SolarSystem {

class Earth extends SolarSystem {

class Mars extends SolarSystem {

public class Moon extends Earth {

    public static void main(String args[])

    {

        SolarSystem s = new SolarSystem();

        Earth e = new Earth();

        Mars m = new Mars();

        [Link](s instanceof SolarSystem);

        [Link](e instanceof Earth);

        [Link](m instanceof SolarSystem);

    }
}

Output
true
true
true
What all can be done in a Subclass?
In sub-classes we can inherit members as is, replace them, hide them, or supplement
them with new members: 
 The inherited fields can be used directly, just like any other fields.
 We can declare new fields in the subclass that are not in the superclass.
 The inherited methods can be used directly as they are.
 We can write a new instance method in the subclass that has the same
signature as the one in the superclass, thus overriding it (as in the example
above, toString() method is overridden).
 We can write a new static method in the subclass that has the same signature
as the one in the superclass, thus hiding it.
 We can declare new methods in the subclass that are not in the superclass.
 We can write a subclass constructor that invokes the constructor of the
superclass, either implicitly or by using the keyword super.

Common questions

Powered by AI

Designing a class hierarchy involves avoiding excessive inheritance depth, which complicates maintenance and understanding. Prefer composition over inheritance for flexibility, clearly delineate responsibility between classes, and ensure that inheritance is used for genuine IS-A relationships. Use abstract classes and interfaces judiciously to provide flexible and reusable components. Test thoroughly to identify and rectify design issues early in development .

In Java, the 'extends' keyword is used to denote that a class is derived from another class, thus establishing an IS-A relationship. This relationship implies that the subclass inherits from the superclass, adopting its fields and methods. The use of 'extends' enables polymorphic behavior and facilitates code reuse, as objects of the subclass type can be treated as objects of the superclass type .

Inheritance, while promoting reusability, can introduce complexity and tight coupling between classes, leading to fragile base class problems where changes in the superclass ripple through subclasses. Java's single inheritance restriction can limit flexibility, although interfaces provide a workaround. Additionally, inheritance can obscure the true object hierarchy if not carefully designed and may lead to issues like the inability to inherit constructors and access to private superclass members without appropriate methods .

Java supports several types of inheritance including single inheritance, multilevel inheritance, hierarchical inheritance, and multiple inheritance through interfaces. Single inheritance allows a subclass to inherit features from one superclass. Multilevel inheritance involves a chain of inheritance where a derived class inherits from another derived class. Hierarchical inheritance occurs when one superclass is inherited by multiple subclasses. Multiple inheritance is achieved through interfaces, allowing a class to inherit features from multiple interfaces, as Java doesn't support multiple inheritances with classes .

Method overriding allows a subclass to provide a specific implementation of a method already defined in its superclass. This is particularly useful in scenarios requiring polymorphic behavior, such as graphical user interface (GUI) design, where different components need tailored behavior. Overriding enhances flexibility and code adaptability, allowing developers to integrate diverse functionalities seamlessly without altering the superclass code .

The 'instanceof' operator allows checking whether an object is an instance of a specific class or interface at runtime. In the context of inheritance, 'instanceof' can be used to verify an object's type along its inheritance hierarchy. This is particularly useful in scenarios where dynamic behavior is needed based on object type, ensuring type safety and facilitating polymorphic operations even when objects are referenced by their superclass type .

In Java, while subclasses inherit fields and methods from their superclass, constructors are not inherited. However, the constructor of the superclass can be invoked within a subclass constructor implicitly or using the 'super' keyword. This distinction is crucial because it affects how initialization is handled when objects are created. Subclasses must ensure proper implementation of constructors, especially when dealing with private fields or when super() calls are necessary for initialization .

Hierarchical inheritance involves multiple subclasses inheriting from a single superclass, which can be beneficial in a modular system where common functionalities are encapsulated in the superclass. This design promotes code reusability, allows easy extension of the system by adding new subclasses without modifying existing code, and enhances maintainability by isolating changes to specific subclasses. For instance, a single base class can define shared properties and methods, while individual subclasses provide specialized implementations .

Java achieves multiple inheritances through interfaces, where a class can implement multiple interfaces and inherit their methods. This approach circumvents the complexity and ambiguity of multiple inheritances in typical class-based systems. It allows for a more flexible design, as a class can adopt behavior from multiple sources, promoting code reusability and scalability without encountering the diamond problem associated with multiple inheritance in other languages .

Access to superclass's public and protected members maintains encapsulation boundaries, allowing modification of superclass code without affecting subclasses. Direct access to private members would breach encapsulation, yet subclasses can interact with these members via public or protected getter and setter methods. This approach preserves encapsulation while granting controlled access, ensuring that manipulation of private fields does not compromise the integrity of the system .

You might also like