Inheritance

Introduction

  1. Inheritance is a type of IS-A relationship that indicates one object is a type of another object.
  2. It is a technique through which one object of a class acquires the behaviors and properties of another object.
  3. For example, a car is a type or kind of vehicle. A car does everything a vehicle can do and stores all the states that a vehicle needs to make these behaviors possible.

Examples

Java Inheritance Example

class BaseClass { 
   public void display() {
      System.out.println("Base Class Display Called");
   }
}

class ChildClass extends BaseClass {
   public void print() {
      display();
   }
}
 
class Main {
   public static void main(String[] args) {
        ChildClass c = new ChildClass();
        c.display();   //call BaseClass method 
        c.print();     //call ChildClass method, which uses the BaseClass method
   }
}

Why do we use inheritance?

  • Code Reusability: Inheritance allows a class to inherit characteristics and behaviors from another class. This means you don’t have to write the same code again and again. Instead, you write a (general) class once and then inherit its attributes and methods in all the classes that need these features.
  • Extensibility: It’s possible to add more features to a class without modifying it, by inheriting a class from it and adding new features to the derived class. This is particularly useful when you want to enhance an existing class without changing its source code.
  • Data Hiding: Child classes can inherit all the public and protected members of the superclass. However, the private members of the superclass are hidden from child classes. This helps in achieving secure code.
  • Code Organisation: Inheritance helps to structure the code in a hierarchical manner, which makes it easier to understand and maintain. It helps in categorizing classes based on their properties and behaviors.

Limitations with Inheritance

Extending a class is the first thing that comes to mind when you need to alter an object’s behavior. However, inheritance has several serious caveats that you need to be aware of.

  • Inheritance is static: You can’t alter the behavior of an existing object at runtime. You can only replace the whole object with another one that’s created from a different subclass.
  • Subclasses can have just one parent class. In most languages, inheritance doesn’t let a class inherit behaviors of multiple classes at the same time.

One of the ways to overcome these caveats is by using Aggregation or Composition instead of Inheritance which you will learn in the next lessons.

Leave a Reply