Inheritance in Java

🧠 What is Inheritance?

Inheritance is one of the core features of OOP. It allows a child class to inherit the properties and behaviors (fields and methods) of a parent class.


πŸ”Έ Types of Inheritance:

  • Single – One subclass, one superclass.

  • Multilevel – Class inherits from a subclass of another.

  • Hierarchical – Multiple classes inherit from one class.

❌ Java doesn’t support multiple inheritance directly using classes.


βœ… Syntax:

class Animal {
void eat() {
System.out.println("This animal eats food.");
}
}

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


πŸ§ͺ Usage:

Dog d = new Dog();
d.eat(); // from Animal
d.bark(); // from Dog

πŸ” Benefits:

  • Promotes code reuse.

  • Helps in method overriding.

  • Supports runtime polymorphism.


πŸ“Œ Key Points:

  • extends keyword is used.

  • The child class inherits all non-private members.

  • Constructors are not inherited, but the parent constructor can be called using super().


 

Related Posts