Introduction to Object-Oriented Programming -2 Inheritance & Polymorphism

https://cdn-images-1.medium.com/max/720/1*I6we8oLHiT9AMdshl4UZsg.png

In this article, we will continue to tackle Object-Oriented Programming- abbr. OOP-. The topics of this article are Inheritance and Polymorphism. These topics are two of the primary characteristics of object-oriented programming.


Inheritance

Inheritance is a concept in which you define parent classes and child classes. So, It is the mechanism by which one class is allowed to inherit the features (fields and methods) of another class. Inheritance gives us reusability. Reusability could be described as creating a new class by reusing the properties of the existing class.

We define the “inheritance concept” into two categories:

C#

class BaseClass
{
 public string model { get; set; }
 public string color { get; set; }
 public void TurnOn() 
 {
  Console.WriteLine("Turn On");
 }
 public void TurnOff() 
 {
  Console.WriteLine("Turn Off");
 }
}
class MacBook : BaseClass
{
 public string display { get; set; }
 public string storage { get; set; }
 public void OpenTerminal() { 
  Console.WriteLine("Terminal Opened"); 
 }
}
class Phone : BaseClass
{
 public string capacity { get; set; }
 public string display { get; set; }
 public void Call(string phoneNumber) 
 {
  Console.WriteLine(phoneNumber + " Calling ");  
 }
}
MacBook macBook = new MacBook();
macBook.model = "MacBook Pro";
macBook.color = "Space Gray";
macBook.display = "13";
macBook.storage = "1 TB";
macBook.TurnOn(); // Turn On
Phone phone = new Phone();
phone.model = "Iphone 12";
phone.color = "Pasific Blue";
phone.capacity = "256 GB";
phone.display = "6.1";
phone.TurnOn(); // Turn On
phone.Call("+90 242 242 2424");// "+90 242 242 2424 Calling"

JavaScript (ES6)

class BaseClass {
  constructor(model, color) {
    this.model = model;
    this.color = color;
  }
  TurnOn() {
    return "Turn On";
  }
  TurnOff() {
    return "Turn Off";
  }
}