๐Ÿฅ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