❔ What is Inheritance?
Inheritance allows a class (child/subclass) to inherit properties and behaviors (variables and methods) from another class (parent/superclass).
Reusability: Write once, use multiple times.
🚀 Why Use Inheritance?
Reuse code from existing classes
Avoid duplication
Support hierarchical classifications
Enables polymorphism and method overriding
🔸 Syntax:
class Parent {
// parent class
}
class Child extends Parent {
// child class inherits Parent
}👨👩👧👦 Real-Life Analogy
Vehicle is a general class. Car and Bike are specific types of vehicles.
Vehicle (Superclass) | Car / Bike (Subclass) |
|---|---|
has wheels | can accelerate |
can move | has gear system |
Example: Single Inheritance
class Animal {
void eat() {
System.out.println("This animal eats food.");
}
}
class Dog extends Animal {
void bark() {
System.out.println("The dog barks.");
}
}
public class Main {
public static void main(String[] args) {
Dog d = new Dog();
d.eat(); // inherited
d.bark(); // own method
}
}This animal eats food.
The dog barks.👪 Types of Inheritance in Java
Type | Description |
|---|---|
Single | One child class inherits one parent class |
Multilevel | Child inherits from a class that also inherits another class |
Hierarchical | Multiple classes inherit from a single class |
❌ Java does not support multiple inheritance (a class inheriting from more than one class) using classes. It supports it via interfaces.
👨👧👦 Multilevel Inheritance Example
class Animal {
void eat() {
System.out.println("Eats food");
}
}
class Dog extends Animal {
void bark() {
System.out.println("Barks");
}
}
class Puppy extends Dog {
void weep() {
System.out.println("Weeps");
}
}
public class Main {
public static void main(String[] args) {
Puppy p = new Puppy();
p.eat(); // from Animal
p.bark(); // from Dog
p.weep(); // from Puppy
}
}Eats food
Barks
Weeps📝 Important Notes
Use
extendskeyword to inheritChild class can access all non-private members of the parent
Constructors are not inherited
Method overriding is common in inheritance