Core Module
12 min forge

Java Inheritance

Hierarchical relationships, 'extends' keyword, and 'super' usage.

Java Inheritance

πŸ“˜ What is it

Inheritance allows one class (Subclass/Child) to acquire the properties and methods of another class (Superclass/Parent). In Java, this is achieved using the extends keyword.

⚑ When to use

Use inheritance to promote code reusability and to establish an "IS-A" relationship (e.g., Eagle IS-A Bird).

πŸ—οΈ Key Concepts

  • super Keyword: Used to refer to the immediate parent class (for methods, variables, or constructors).
  • Method Overriding: Providing a specific implementation for a method already defined in the parent class.
  • Single Inheritance: Java supports only single inheritance for classes (a class can only extend one class).

πŸ’» Code example

java Standard
class Animal { void eat() { System.out.println("Eating..."); } } class Dog extends Animal { @Override void eat() { super.eat(); // Call base version System.out.println("Dog is eating kibble."); } void bark() { System.out.println("Woof!"); } } public class Main { public static void main(String[] args) { Dog myDog = new Dog(); myDog.eat(); // Calls overridden version myDog.bark(); } }

❌ Common mistakes

  • Multiple Inheritance: Trying to extends more than one class (use Interfaces for this).
  • Private Access: Expecting to inherit private members (they are not inherited).
  • Circular Inheritance: Class A extends B, and B extends A (not allowed).