🧬 Inheritance in Java – Explained Simply
Inheritance is one of the fundamental principles of Object-Oriented Programming (OOP). In Java, inheritance allows a class to acquire properties (fields) and behaviors (methods) from another class.
🧠 Why Use Inheritance?
Benefit | Description |
---|---|
🔁 Code Reusability | Avoid rewriting common code in multiple classes |
🧩 Extensibility | Add new features without modifying existing code |
🧼 Clean Code | Organize classes hierarchically |
🚀 Polymorphism Support | Enable dynamic method binding via method overriding |
📦 Types of Inheritance in Java
Type | Supported in Java? | Example |
---|---|---|
Single Inheritance | ✅ Yes | One class inherits another |
Multilevel | ✅ Yes | Class → Subclass → Sub-subclass |
Hierarchical | ✅ Yes | One parent → many children |
Multiple | ❌ No (via classes) | Java supports via interfaces |
🧱 Syntax: extends
Keyword
class Animal {
void eat() {
System.out.println("This animal eats food.");
}
}
// Dog inherits from Animal
class Dog extends Animal {
void bark() {
System.out.println("Dog barks.");
}
}
🔎 Usage:
🧠 Method Overriding
You can override parent class methods in the child class:
🛡️ Access Modifiers and Inheritance
class Animal {
void sound() {
System.out.println("Some generic sound.");
}
}
class Cat extends Animal {
@Override
void sound() {
System.out.println("Meow");
}
}
📌 Summary
Term | Meaning |
---|---|
extends |
Keyword used for inheritance |
Superclass | The parent/base class |
Subclass | The child/derived class |
Method overriding | Redefining parent method in child class |
Code reuse | Main benefit of inheritance |