Java (programming language)

Inheritance in Java with Examples


Inheritance is a fundamental object-oriented programming (OOP) concept that enables the creation of new classes (subclasses) based on existing ones (parent classes or superclasses). Subclassing allows you to:

  • Reuse code: Subclasses inherit fields and methods from their parent class, reducing redundancy and promoting code maintainability.
  • Extend functionality: Subclasses can add new fields and methods, tailoring the inherited behavior to specific needs.
  • Model real-world relationships: Inheritance mirrors hierarchical relationships between objects, like “Car is a type of Vehicle.”

Key Concepts

  • extends keyword: To create a subclass, use extends followed by the parent class name:


class Subclass extends Superclass {
    // ...
  • IS-A relationship: Inheritance represents an “is-a” relationship between classes. A subclass is a specialized version of its superclass.

Basic Example


class Animal {
    public void eat() {

class Dog extends Animal {
    public void bark() {
  • Dog inherits the eat() method from Animal.
  • Dog adds its own bark() method.

Accessing Superclass Members

  • Use super to access superclass members from a subclass:


class Bird extends Animal {
    public void fly() {

    public void eat() {; // Call the superclass eat() method
        System.out.println("Pecking for seeds...");

Method Overriding

  • Subclasses can override inherited methods to provide specialized behavior:


class Cat extends Animal {
    public void eat() {
        System.out.println("Eating cat food...");

Types of Inheritance

  • Single Inheritance: A subclass inherits from one superclass.
  • Multilevel Inheritance: A subclass inherits from a subclass, creating a chain of inheritance.
  • Hierarchical Inheritance: Multiple subclasses inherit from a single superclass.
  • Multiple Inheritance: A subclass inherits from multiple superclasses (not directly supported in Java, but achievable through interfaces).

When to Use Inheritance

  • Code reuse and avoiding redundancy.
  • Extending functionality of existing classes.
  • Modeling real-world hierarchical relationships.
  • Creating class hierarchies for better organization.


Inheritance is a powerful OOP tool for code organization, reusability, and extensibility. Understanding its principles and applications is essential for designing well-structured and maintainable Java applications.


Learn coding the easy way. Find programming guides, examples and solutions with explanations.

Related Articles

Leave a Reply

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

Back to top button