With the introduction of OOPs, Inheritance and Composition entered our senses and still confusing us.

Choosing between Composition and Inheritance is not easy. Often, the decision depends upon the information which is not yet there.

The structure of an application plays an essential role in adding changes. Composition and Inheritance are the building blocks of an application structure. It is imperative to know when to use which one.

Inheritance

Inheritance is a way of reusing code by inheriting the structure from the referred class or Type. The referred class is called

parent or base class and the referring class is called child or subclass.

Inheriting the structure suggests that subclass inherits public members (API) of the parent class. A subclass can override or add new behaviour or extend the existing behaviour of the parent class.

// Reference class
class Animal {
   fun walk() {
     println("animal walk");
   }

   fun speak() {
      println("...")
   }
}

// Referring Class
// Cat class "inherits the structure" from the Animal class
class Cat : Animal {

   // overriding existing behaviour
   fun speak() {
      println("meow")
   }
}

// in main
val cat = Cat();
cat.walk() // Cat can "reuse" parent class behavior
cat.speak() // meow

#data-science

Difference Between Inheritance And Composition
1.95 GEEK