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.
What is Object Oriented Programming?
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.
Objects in Real Life and in OOP
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.
Inheritance: The Key to the Hierarchy
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: Protecting your Secrets
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: The Magic of Versatility
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.
Conclusion: OOP... put it into Action
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing
