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
superKeyword: 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 Standardclass 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
extendsmore than one class (use Interfaces for this). - Private Access: Expecting to inherit
privatemembers (they are not inherited). - Circular Inheritance: Class A extends B, and B extends A (not allowed).