Java Inheritance

What is Inheritance?

Inheritance allows one class to inherit properties and methods from another class. This helps reduce code duplication and models real-world relationships.

For example, a Dog is an Animal, so Dog can inherit common behavior from Animal.

Loading...
Output:

Creating a Subclass

Use the extends keyword to create a subclass. The subclass automatically gets access to the parent class's public and protected members.

Loading...
Output:

Using Inheritance

Once a class extends another, objects of the child class can use both its own methods and inherited methods from the parent class.

Loading...
Output:

Method Overriding

A subclass can override a method from the parent class to provide its own implementation. Use @Override for clarity and error checking.

Loading...
Output:

The super Keyword

The super keyword refers to the parent class. It is commonly used to call the parent constructor or access parent methods.

Loading...
Output:

Inheritance Hierarchy

Java supports multi-level inheritance, where classes can extend other subclasses, forming a hierarchy.

Loading...
Output:

Rules and Limitations

Java allows a class to extend only one class (single inheritance). Constructors are not inherited, and private members cannot be accessed directly.

  • Only one parent class allowed
  • Constructors are not inherited
  • Private fields are not directly accessible

Practice

Create a Vehicle class and a Car subclass that overrides the start() method.

Loading...
Output:

Need Help?