Home > Article > Web Front-end > Object Oriented Programming - An abstraction of reality
Hello, in this article, which seems like a tutorial, we will address a topic that in particular at first gave me a lot of headaches. However, this difficulty led me to study, study and study to make the abstraction of everyday life my own and thus bring to lines of code, the representation of something tangible (believe me, this can be a titanic task at times) . I became so passionate about the topic that I now share in this article important data to understand it, so let's get to the heart of the matter.
I will explain or try to do it in the best way possible, object-oriented programming or by its acronym (OOP) using JavaScript as my language of choice. To understand how to apply OOP to real-world situations, you have to internalize that object-oriented programming is not just a technique, it's an approach to life! In this article, we will explore fundamental OOP concepts and apply them to tangible examples from everyday life.
Object-oriented programming is a programming paradigm that is based on the concept of "objects", you can imagine at this very moment literally an object of life: an apple, a dog, a house, a car, a rubber daddy. Now, visualize that these objects can contain data in the form of properties or characteristics and functionalities, that is, they can do things. Imagine that you are modeling a virtual world where each entity can be represented as an independent object with unique characteristics.
To better understand OOP, let's take a look at a real-life example: a car. A car can have properties such as model, color and speed, as well as methods such as starting and stopping. Transpolating this to the world of OOP would be quite simple:
class Auto { constructor(modelo, color) { this.modelo = modelo; this.color = color; this.velocidad = 0; } arrancar() { console.log(`El auto ${this.modelo} ha arrancado.`); } detener() { console.log(`El auto ${this.modelo} se ha detenido.`); this.velocidad = 0; } acelerar(kmh) { this.velocidad += kmh; console.log(`El auto ${this.modelo} acelera a ${this.velocidad} km/h.`); } } // Crear un objeto auto const miAuto = new Auto('Sedán', 'Rojo'); // Utilizar métodos del objeto auto miAuto.arrancar(); miAuto.acelerar(50); miAuto.detener();
In this example, we have created a class Auto with properties such as model, color and speed, as well as methods, that is, the things it can do: like start, stop and accelerate. Then, we create a myAuto object based on this class and use it to simulate real-life actions.
Imagine now that we want to model not only cars, but also motorcycles. They both share some similarities, but also have unique characteristics. This is where the concept of inheritance in OOP comes into play.
class Camioneta extends Auto { constructor(modelo, color, tipo) { super(modelo, color); this.tipo = tipo; } realizarTruco() { console.log(`La camioneta ${this.modelo} ${this.tipo} realiza un asombroso truco.`); } } // Crear un objeto camioneta const miCamioneta = new Camioneta('Explorer', 'Negra', '4x4'); // Utilizar métodos del objeto camioneta miCamioneta.arrancar(); miCamioneta.acelerar(80); miCamioneta.realizarTruco(); miCamioneta.detener();
Here, we have created a new Truck class that extends the Car class. The extends keyword allows us to inherit all the properties and methods of the parent class (Auto). Additionally, the child class (Pickup) can have additional properties and methods.
Encapsulation is another pillar of OOP that allows us to protect the internal details of an object and expose only what is necessary. Let's look at a simple example using a "Bank Account":
class CuentaBancaria { constructor(titular, saldoInicial) { this.titular = titular; this._saldo = saldoInicial; // El saldo se designa con el prefijo _ para indicar que es privado } get saldo() { return this._saldo; } depositar(cantidad) { if (cantidad > 0) { this._saldo += cantidad; console.log(`${cantidad} depositados. Nuevo saldo: ${this._saldo}`); } else { console.log("Error: La cantidad debe ser mayor que cero."); } } retirar(cantidad) { if (cantidad > 0 && cantidad <= this._saldo) { this._saldo -= cantidad; console.log(`${cantidad} retirados. Nuevo saldo: ${this._saldo}`); } else { console.log("Error: Cantidad inválida o saldo insuficiente."); } } } // Crear una cuenta bancaria const miCuenta = new CuentaBancaria('Juan Pérez', 1000); // Utilizar métodos del objeto cuenta bancaria console.log(`Saldo inicial: ${miCuenta.saldo}`); miCuenta.depositar(500); miCuenta.retirar(200);
In this example, we have encapsulated the account balance using a get method to access it. This protects the balance from being modified directly from outside the class, maintaining the integrity of our bank account.
Polymorphism allows different classes to share the same method name, but with specific behaviors for each one. To illustrate this, let's imagine a zoo with animals that make sounds.
class Animal { hacerSonido() { console.log('Algunos sonidos genéricos de animal.'); } } class Perro extends Animal { hacerSonido() { console.log('¡Guau! ¡Guau!'); } } class Gato extends Animal { hacerSonido() { console.log('¡Miau! ¡Miau!'); } } // Crear objetos animales const miAnimal = new Animal(); const miPerro = new Perro(); const miGato = new Gato(); // Utilizar el método hacerSonido de cada objeto miAnimal.hacerSonido(); miPerro.hacerSonido(); miGato.hacerSonido();
In this example, the Dog and Cat classes inherit from the Animal class, but each overrides the makeSound method with its own unique implementation. This allows different types of animals to use the same method differently.
I really appreciate you reaching this point! We explore key concepts such as objects, inheritance, encapsulation and polymorphism, and have applied them to real-life situations. Remember, OOP is a way of thinking that allows you to model and understand the world more effectively...and put it into code.
So the next time you see a car, a bank account, or even your pet, think about how you could represent them as objects in your code. Object-oriented programming is not only a powerful tool, it's a way to bring your programs to life!
I hope you have enjoyed this article and that you can take advantage of it in your projects. Leave me your comments to let me know what you thought and if you have any other real-life abstractions. ;)
The above is the detailed content of Object Oriented Programming - An abstraction of reality. For more information, please follow other related articles on the PHP Chinese website!