← Back to Chapters

Java Inheritance

? Java Inheritance

? Quick Overview

Inheritance is a core concept of Object-Oriented Programming in Java. It allows one class to acquire the properties and methods of another class, promoting code reusability and hierarchical relationships.

? Key Concepts

  • Uses the extends keyword
  • Supports single inheritance with classes
  • Enables method overriding
  • Improves code reuse and maintainability

? Syntax / Theory

A child class (subclass) inherits from a parent class (superclass). The subclass can use existing methods and also define new behavior.

? View Code Example
// Parent class definition
class Animal {
void sound() {
System.out.println("Animal makes a sound");
}
}

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

// Main class to test inheritance
public class Main {
public static void main(String[] args) {
Dog d = new Dog();
d.sound();
d.bark();
}
}

? Live Output / Explanation

Output

Animal makes a sound
Dog barks

The Dog class automatically gets access to the sound() method from the Animal class due to inheritance.

? Interactive Simulator: Vehicle Hierarchy
Parent: Vehicle
method: startEngine()
⬇️ extends
Child: SportsCar
method: turboBoost()

Create Object: SportsCar s = new SportsCar();

// Output will appear here...

? Tips & Best Practices

  • Use inheritance only when an IS-A relationship exists
  • Prefer method overriding instead of duplicating logic
  • Keep parent classes generic and reusable

? Try It Yourself

  • Create a Vehicle class and inherit it in a Car class
  • Override a method in the child class
  • Test behavior using parent class references