DEV Community

PRIYA K
PRIYA K

Posted on

Inheritance in java

Inheritance in Java with Examples

Inheritance in Java is a concept that acquires the properties from one class to other classes; it's a parent-child relationship.

mygreatlearning.com

Inheritance in Java - GeeksforGeeks

Your All-in-One Learning Portal: GeeksforGeeks is a comprehensive educational platform that empowers learners across domains-spanning computer science and programming, school education, upskilling, commerce, software tools, competitive exams, and more.

favicon geeksforgeeks.org



  • One Of the object-oriented
  • Allows one class(subclass or child) to acquire or inherit fields and methods of another class(superclass or parent )
  • field => Global variable
    static and non-static variables.

  • Inheritance enables derivative classes to receive the features of base classes.
    establishes a hierarchical relationship between classes.
    Inheritance is used to create a new class that is a type of an existing class. It helps in extending the functionality of a class without modifying it, thereby adhering to the Open/Closed Principle of software design.
    In OOP, computer programs are designed in such a way where everything is an object that interacts with one another. Inheritance is an integral part of Java OOPs which lets the properties of one class to be inherited by the other.

  1. Parent class ( Super or Base class )

  2. Child class ( Subclass or Derived class )

Benefits of Using Inheritance in Java
Code Reusability: Inheritance allows subclasses to reuse code from the parent class.
code reusability by promoting IS A relationship

  • Creating a new class from the existing class
  • It helps in code reuse and establishes a relationship between classes.(parent class or child class)
  • While Multiple and Hybrid inheritance are not supported using classes, they can be achieved using Interfaces

    Maintainability: Changes in the superclass reflect automatically in the subclasses, making maintenance easier.

    Polymorphism: Allows the method of a subclass to be invoked, even when using the superclass reference.

Avoid Deep Inheritance Hierarchies: Keep inheritance hierarchies shallow to maintain simplicity and reduce complexity.

Prefer Composition Over Inheritance: Consider using composition (has-a relationship) instead of inheritance when appropriate, as it offers more flexibility.

Use @override Annotation: Always use the @override annotation when overriding methods to improve code readability and prevent errors.

Access Control: Use the protected access modifier for superclass members that should be accessible in subclasses but not to the outside world.

Common Inheritance Pitfalls in Java
Tight Coupling: Subclasses can become tightly coupled to their superclasses, making changes difficult.

Overridden Method Confusion: If methods are overridden incorrectly, it may lead to unexpected results.

Lack of Flexibility in Inheriting Multiple Classes: Java doesn't allow multiple inheritance directly, which can lead to limitations when modeling complex relationships.
Enter fullscreen mode Exit fullscreen mode

Class
Blueprint from which objects are created
A class is a group of objects which have common properties. It is a
template or blueprint from which objects are created.

Reusablity: As the name specifies, reusablity is a mechanism which
facilitates you to reuse the fields and methods of the existing class when you create a new class. You can use the same fields and methods already defined in the previous class.

Super class (Parent):
The existing class whose features are inherited.
the class being inherited from
Class whose properties are inherited
Super class is the class from where a subclass inherits the features. It is also called a base class or a parent class.
A class whose properties and methods are inherited by another class.

Subclass (Child):
The new class that inherits features and can add its own unique fields or methods.
It is also called a derived class, extended class, or child class.
the class that inherits from another class
A subclass can reuse the fields and methods of the parent class without rewriting the code
A subclass can add its own fields and methods or modify existing ones to extend functionality.
A class that inherits the properties and methods from a superclass.

extends Keyword:
The specific keyword used to perform inheritance between classes.
In Java, inheritance is implemented using the extends keyword.
The extends keyword in Java code enables inheritance through which child classes automatically obtain attributes and behaviors from parent classes.
Used by the subclass to inherit from the superclass.

super Keyword:
Used inside a subclass to refer to immediate parent class members, such as variables, methods, or constructors.

Syntax

    class Parent {
        // fields and methods
    }
    class Child extends Parent {

        // additional fields and methods

    }
Enter fullscreen mode Exit fullscreen mode

Example

// Parent class
class Animal {
    void eat() {
        System.out.println("This animal eats food.");
    }
}

// Child class
class Dog extends Animal {
    void bark() {
        System.out.println("The dog barks.");
    }
}

// Main class
public class Main {
    public static void main(String[] args) {
        Dog d = new Dog();
        d.eat();   // inherited from Animal
        d.bark();  // defined in Dog
    }
}
Enter fullscreen mode Exit fullscreen mode

Output

Types Of Inheritance
1. Single Inheritance
A sub-class is derived from only one super class. It inherits the properties and behavior of a single-parent class. Sometimes, it is also known as simple inheritance.
A subclass inherits from exactly one superclass.

2. Multilevel Inheritance
A derived class will be inheriting a base class and as well as the derived class also acts as the base class for other classes.
there is a chain of inheritance.
A subclass inherits from another subclass, forming a chain.
a class is derived from another class, which is also a subclass of another class.

// Parent class
class Animal {
void eat() {
        System.out.println("This animal eats food.");
    }
}

// Child class
class Dog extends Animal {
void bark() {
        System.out.println("The dog barks.");
    }
}

class Puppy extends Dog{
void weep(){
        System.out.println("The puppy weeps.");
    }
}

// Main class
public class MultiLevelInheritance {
    public static void main(String[] args) {
        Puppy p = new Puppy();
        p.eat();   // inherited from Animal
        p.bark();  // defined in Dog
        p.weep();
    }
}

Enter fullscreen mode Exit fullscreen mode

3. Hierarchical Inheritance
more than one subclass is inherited from a single base class. i.e. more than one derived class is created from a single base class.
Multiple subclasses inherit from a single parent class or superclasses.

// Parent class
class Animal {
    void eat() {
        System.out.println("Animal eats food");
    }
}

// Child 1
class Dog extends Animal {
    void bark() {
        System.out.println("Dog barks");
    }
}

// Child 2
class Cat extends Animal {
    void meow() {
        System.out.println("Cat meows");
    }
}

// Main class
public class HierarchicalInheritance {
    public static void main(String[] args) {

        Dog d = new Dog();
        d.eat();
        d.bark();

        Cat c = new Cat();
        c.eat();
        c.meow();
    }
}
Enter fullscreen mode Exit fullscreen mode

4. Multiple Inheritance (Through Interfaces)
In Multiple inheritances, one class can have more than one superclass and inherit features from all parent classes.
One class inherits from more than one parent class. Not supported for classes in Java to avoid ambiguity (the Diamond Problem).

Note: that Java does not support multiple inheritances with classes. In Java, we can achieve multiple inheritances only through Interfaces.  A class can implement multiple interfaces.
Enter fullscreen mode Exit fullscreen mode
// Interface 1
interface Animal {
    void eat();
}

// Interface 2
interface Pet {
    void play();
}

// Class implementing both interfaces
class Dog implements Animal, Pet {

    public void eat() {
        System.out.println("Dog eats food");
    }

    public void play() {
        System.out.println("Dog plays");
    }

    void bark() {
        System.out.println("Dog barks");
    }
}

// Main class
public class MultipleInheritance {
    public static void main(String[] args) {
        Dog d = new Dog();
        d.eat();
        d.play();
        d.bark();
    }
}
Enter fullscreen mode Exit fullscreen mode

5. Hybrid Inheritance
It is a mix of two or more of the above types of inheritance. In Java, we can achieve hybrid inheritance only through Interfaces if we want to involve multiple inheritance to implement Hybrid inheritance.
A combination of two or more types of inheritance.

// Base class
class Animal {
    void eat() {
        System.out.println("Animal eats food");
    }
}

// Interface 1
interface Pet {
    void play();
}

// Interface 2
interface Guard {
    void protect();
}

// Hybrid: extends class + implements interfaces
class Dog extends Animal implements Pet, Guard {

    public void play() {
        System.out.println("Dog plays");
    }

    public void protect() {
        System.out.println("Dog protects house");
    }

    void bark() {
        System.out.println("Dog barks");
    }
}

// Main class
public class HybridInheritance {
    public static void main(String[] args) {
        Dog d = new Dog();

        d.eat();     // from Animal
        d.play();    // from Pet
        d.protect(); // from Guard
        d.bark();    // own method
    }
}
Enter fullscreen mode Exit fullscreen mode

6.Constructor Inheritance in Java
constructors are not inherited by subclasses, but they can be invoked using super(). The constructor of the superclass is called before the subclass's constructor.

Why Use Inheritance?
Code Reusability: Subclasses reuse the parent class's code without redefining it.
Method Overriding: Subclasses can provide specific implementations for methods defined in the parent, enabling Runtime Polymorphism.
Logical Organization: It helps organize classes into a clear, tree-like hierarchy that reflects real-world relationships

Important Rules & Constraints
Access Control: Subclasses do not inherit private members of the superclass. They inherit public and protected members.
Constructors: These are not inherited, but a subclass must call the superclass constructor (implicitly or via super()) as the first statement in its own constructor.
Final Keyword: A class declared as final cannot be inherited, and a method declared as final cannot be overridden.Implicit Parent: If no superclass is specified, every Java class implicitly inherits from the Object class.

The final Keyword
If you don't want other classes to inherit from a class, use the final keyword:
If you try to access a final class, Java will generate an error:

final class Vehicle {
  ...
}

class Car extends Vehicle {
  ...
}
Enter fullscreen mode Exit fullscreen mode

Output

The output will be something like this:
Main.java:9: error: cannot inherit from final Vehicle
class Main extends Vehicle {
^
1 error)

Frequently Asked Questions

  1. Why is multiple inheritance (of classes) not supported in Java?

Java does not support multiple inheritance with classes to avoid the diamond problem, where ambiguity arises if two parent classes have the same method. This ensures cleaner, less error-prone code.

  1. How can we achieve multiple inheritance in Java?

In Java, multiple inheritance is achieved through interfaces. A class can implement multiple interfaces, inheriting methods from each without ambiguity.

Also Read: Difference between abstract classes and interfaces in Java

  1. Can constructors be inherited in Java?

Constructors are not inherited in Java, but a subclass can call the constructor of its superclass using the super() keyword to initialize the parent class.

Top comments (0)