🐥Inheritance

👪 What is Inheritance?

Inheritance in Java allows a class to inherit attributes and behaviors from another class. This promotes code reuse and establishes hierarchical relationships between classes.

Why use inheritance in java

  • For Method Overriding (so runtime polymorphism can be achieved).

  • For Code Reusability.

💡 Rules for Inheritance in Java 👨‍💻

Inheritance in Java follows these main rules:

  • 🟢 Uses "extends" keyword to inherit from superclass

class Dog extends Animal {
  //...
}
  • 🟡 Subclasses inherit public and protected members

  • 🔴 Private members not inherited

  • 🟣 Single inheritance - one superclass allowed

  • 🟢 Subclass can override superclass methods

@Override
int getAge() {
  // overridden method
}
  • 🟡 Overridden methods must have same signature

  • 🟢 Use super() to call superclass constructor

  • 🟢 Subclass can declare new members

  • 🟡 Subclass can reuse superclass code

  • 🔵 Inheritance represents an "is-a" relationship

  • 🟣 Use interfaces for "has-a" relationship

  • 🔴 Avoid overusing inheritance where aggregation works better

Inheritance enables code reuse and establishes rich relationships between classes. But careful design is needed to maximize benefits.

👨‍👦 Parent and Child Classes

In Java, classes can inherit from other classes using the extends keyword:

public class Vehicle {

  public void startEngine() {
    System.out.println("Engine started.");
  }

}

public class Car extends Vehicle {
  // Car inherits the startEngine method from Vehicle
} 

Here Car inherits from the Vehicle class.

🔀 Key Notes

  • Inheritance allows a class to inherit from another parent class

  • The child class gets all the members of the parent class

  • This establishes a hierarchical parent-child relationship

  • Inheritance supports code reuse in Java

So with inheritance, classes can reuse logic in other classes!

👨‍👦 In Simple Terms

Inheritance allows classes to form hierarchical parent-child relationships, just like children inherit genes and traits from their parents.

The child class automatically gets the fields and methods of the parent class, allowing code reuse.

So in Java, inheritance represents parent-child class relationships!

Last updated