BEFORE Programming 101 : OOP

BEFORE Programming 101 : OOP

Mastering Object-Oriented Programming: Unleashing the Power of Objectivity in Code Creation.

As For The Previous Section which you can check it Here, In This Article we will discover three main components of OOP :

  • Inheritance.

  • Encapsulation.

  • Polymorphism.

Inheritance :

Inheritance is a fundamental concept in object-oriented programming (OOP) that allows a new class to be based on an existing class. The new class, also known as the derived class or subclass, inherits the properties and methods of the existing class, known as the base class or superclass.

By using inheritance, you can create a new class that is a modified version of an existing class. This can save time and reduce code duplication, as you can reuse the code from the base class and only add or modify the code that is specific to the new class.

\=> What About An Example In Python :

class Animal:
    def __init__(self, name):
        self.name = name

    def speak(self):
        pass

class Dog(Animal):
    def speak(self):
        return "Woof!"

class Cat(Animal):
    def speak(self):
        return "Meow!"

dog = Dog("Fido")
cat = Cat("Whiskers")

print(dog.name + ": " + dog.speak())
print(cat.name + ": " + cat.speak())

In this example, we have a base class called Animal with a constructor that takes a name parameter and a method called speak that is not implemented. We also have two derived classes called Dog and Cat that inherit from the Animal class,

The Dog class and Cat class each have their own implementation of the speak method.

\=> JavaScript :

class Animal {
  constructor(name) {
    this.name = name;
  }

  speak() {
    return "";
  }
}

class Dog extends Animal {
  speak() {
    return "Woof!";
  }
}

class Cat extends Animal {
  speak() {
    return "Meow!";
  }
}

let dog = new Dog("Fido");
let cat = new Cat("Whiskers");

console.log(dog.name + ": " + dog.speak());
console.log(cat.name + ": " + cat.speak());

Encapsulation:

Encapsulation is a fundamental concept in object-oriented programming that refers to the bundling of data and methods that operate on that data into a single unit, known as a class. The main idea behind encapsulation is to hide the internal details of the class from outside code, and to provide a well-defined interface for accessing and manipulating the data.

In Addition , Encapsulation provides several benefits, including improved security, modularity, and maintainability of code. By hiding the internal details of a class, encapsulation makes it easier to modify the implementation of the class without affecting other parts of the code. It also reduces the risk of unintended side effects from changes to the internal state of the object, and helps to prevent errors caused by invalid or inconsistent data.

\=> In Python, encapsulation is achieved through the use of private and public class attributes and methods. Here's an example that demonstrates how encapsulation can be implemented in Python:

class Car:
    def __init__(self, make, model, year):
        self.__make = make
        self.__model = model
        self.__year = year

    def get_make(self):
        return self.__make

    def set_make(self, make):
        self.__make = make

    def get_model(self):
        return self.__model

    def set_model(self, model):
        self.__model = model

    def get_year(self):
        return self.__year

    def set_year(self, year):
        self.__year = year

car = Car("Honda", "Civic", 2022)
print(car.get_make())
car.set_make("Toyota")
print(car.get_make())

In this example, we have a Car class with three private attributes: __make, __model, and __year. These attributes are prefixed with double underscores to indicate that they are private and should not be accessed directly from outside the class.

To provide access to these private attributes, we define public Setter And Getter methods for each attribute.

\=> In JavaScript, encapsulation can be achieved using closures to create private variables and functions. Here's an example that demonstrates how encapsulation can be implemented in JavaScript :

function Car(make, model, year) {
  let _make = make;
  let _model = model;
  let _year = year;

  this.getMake = function() {
    return _make;
  }

  this.setMake = function(make) {
    _make = make;
  }

  this.getModel = function() {
    return _model;
  }

  this.setModel = function(model) {
    _model = model;
  }

  this.getYear = function() {
    return _year;
  }

  this.setYear = function(year) {
    _year = year;
  }
}

let car = new Car("Honda", "Civic", 2022);
console.log(car.getMake());
car.setMake("Toyota");
console.log(car.getMake());

In this example, we define a Car constructor function that takes three parameters: make, model, and year. Inside the constructor function, we create three private variables using let statements, which are only accessible inside the closure created by the constructor function.

Polymorphism:

Polymorphism is a concept in object-oriented programming that allows objects of different classes to be treated as if they were objects of the same class. It means that different objects can be used interchangeably, even though they may have different implementations.

There are two types of polymorphism: compile-time polymorphism and runtime polymorphism. Compile-time polymorphism is achieved through function overloading, while runtime polymorphism is achieved through method overriding.

\=> Here's an example to illustrate polymorphism in Python using method overriding:

class Animal:
    def make_sound(self):
        pass

class Dog(Animal):
    def make_sound(self):
        print("Woof!")

class Cat(Animal):
    def make_sound(self):
        print("Meow!")

animals = [Dog(), Cat()]

for animal in animals:
    animal.make_sound()

\=> here's the same example of polymorphism in JavaScript:

class Animal {
  makeSound() {
    console.log("The animal makes a sound");
  }
}

class Dog extends Animal {
  makeSound() {
    console.log("The dog barks");
  }
}

class Cat extends Animal {
  makeSound() {
    console.log("The cat meows");
  }
}

// Create a list of Animal objects
const animalList = [new Dog(), new Cat(), new Dog(), new Cat()];

// Loop through the list and call the makeSound() method on each object
for (let animal of animalList) {
  animal.makeSound();
}

We create a list animals that contains instances of both Dog and Cat, and then loop through the list and call the make_sound() method on each object. Because each object is an instance of a different class, the appropriate implementation of the make_sound() method is called for each object. This demonstrates how polymorphism allows objects of different classes to be treated as if they were objects of the same class, and how method overriding allows each subclass to provide its own implementation of a method defined in its superclass.

Conclusion :

Object-oriented programming is a powerful paradigm that offers many benefits, including code reusability, modularity, and flexibility. By organizing code into classes and objects, we can better model real-world concepts and create more robust and maintainable software. Additionally, OOP provides us with useful concepts such as encapsulation, inheritance, and polymorphism, which enable us to write code that is easier to understand and maintain. By embracing the principles of OOP, we can write more efficient and effective code that meets the needs of today's complex software applications.