Object-Oriented Programming (POO) Comprehensive Notes
What is Object-Oriented Programming (OOP)
- Programming paradigm that “translates” real-world objects into program code.
- Real-world object anatomy
- State – current condition (e.g., a car can be stopped, moving, parked).
- Properties / Attributes – descriptive data (e.g., color, weight, size).
- Behaviour / Methods – actions it can perform (e.g., start, brake, accelerate, turn).
- Goal: write programs composed of interacting objects that mirror these real-life characteristics.
- Common OOP languages: C++, Java, Visual .NET, JavaScript, etc.
- Advantages
- Modularisation – programs divided into reusable “chunks” (classes/modules).
- Reusability – inheritance lets you extend existing code with minimal duplication.
- Robustness – structured exception handling keeps the rest of the program running if one module fails.
- Encapsulation – internal details are hidden; objects expose safe public interfaces.
Core OOP Vocabulary
- Abstraction – focusing on essential qualities rather than concrete details.
- Class – blueprint that lists common attributes & behaviours for a group of objects.
- Object / Instance / Ejemplar – concrete realisation of a class.
- Instantiation – the act of creating an object from a class.
- Modularisation – organising code into independent, interchangeable units.
- Encapsulation / Encapsulación – bundling data with code that operates on it, restricting direct external access.
- Inheritance – mechanism by which one class acquires the properties & behaviours of another.
- Polymorphism – ability for a single interface to represent different underlying forms (e.g., method overriding).
Class vs Object Explained (Car Example)
- Class Coche (Car) – blueprint with:
- Properties: color, peso, alto, largo.
- Methods: arrancar, frenar, girar, acelerar.
- Object Renault – instance of Coche.
- Accessing properties (pseudo-code)
Renault.color = "rojo";Renault.peso = 1500; - Accessing behaviour
Renault.arranca();Renault.frena();
Dot Notation in JavaScript
- General syntax:
object.property or object.method(). - Hierarchical chaining:
document.write(), window.alert(). - DOM examples:
boton.style.width = "600px";boton.focus();
Practical DOM Examples (HTML + JS)
- Create a
<button id="boton1"> in HTML. - JS workflow:
let miboton = document.getElementById("boton1"); (object reference)- Change size/background:
miboton.style.width = "200px";miboton.style.backgroundColor = "red";
- Multiple elements example:
- Buttons
boton1, boton2, and input#mitexto1. - Set width/height =50\text{px}, move focus:
miboton2.focus();. - Colour text box background pink and height =20\text{px}.
Using the Built-in Date Object
- Instantiate:
let fecha = new Date(); - Extract components:
getDate() → day number.getDay() → day of week 0\text{–}6.getMonth() → month 0\text{–}11.getFullYear() → 4-digit year.
- Convert numeric values to Spanish words via
switch or arrays.- Arrays:
dias[] = ["Lunes", … "Domingo"], meses[] = ["Enero" … "Diciembre"].
- Compose readable string:
`${dias[dia-1]}, ${diaNum} de ${meses[mes]} de ${anio}`
- Example output: “Martes, 29 de Octubre del 2024”.
- Attributes:
nombre, apellidos, correo, tfno. - Constructor initialises all attributes.
- Method
verInfo() returns formatted HTML string with contact details. - Setters (two styles)
- Traditional:
establecerNombre(nombre){ … } - ES6 property style:
set establecerNombre(nombre){ … }
2. Using the Base Class
- Instantiation:
let persona1 = new Contacto("Juan", "Santos", "micorreo@gmail.com", "653987456"); - Display:
document.write("<div>" + persona1.verInfo() + "</div>"); - Modify attribute via setter then re-display.
- Declared with
class ContactoFamiliar extends Contacto. - Adds new attribute
parentesco (relationship). - Overrides
verInfo(); calls super.verInfo() then appends parentesco. - Instantiation:
let persona2 = new ContactoFamiliar("Romualdo", … , "cuñado");
4. Managing Collections
let contactos = [];contactos.push(new Contacto(...));- Iterate with
forEach and call verInfo() on each.
5. Static Class Members
- Static variable:
static cantidad = 0; counts how many contacts exist.- Increment inside constructor:
Contacto.cantidad++;
- Static method:
static mostrar_instrucciones(){ … } – can be invoked as Contacto.mostrar_instrucciones(); without any object. - Display total contacts:
`La cantidad total de contactos es: ${Contacto.cantidad}`
Access Modifiers in Modern JavaScript (ES2022)
- Public (default) – accessible everywhere.
- Private – prefix with
# (e.g., #telefono). Only available inside the class body. - Protected – not natively supported; developer convention uses an underscore (e.g.,
_direccion).
Telephone Class – Proposed Exercise
- Attributes
color, peso, dimensionPantalla, tipoCamara, memoriaRAM, precio.
- Behaviours
encender() – toggles encendido/apagado; prints appropriate message.reiniciar() – only if phone is on.tomarFoto() – prints “Foto realizada”.grabarVideo() – prints “Video grabado”.
- Advanced Variants
- Alta Gama phone (inherits base class) – adds
camaraSuperLenta, camaraExtra, reconocimientoFacial. - Gama Media phone – adds
huellaDactilar recognition.
- Task – create 3 high-end and 2 mid-range objects, display their characteristics, and determine (e.g., with
Math.max) which has the highest precio.
Practical & Real-World Relevance
- Modular design mirrors real-life systems (car, phone, contact agenda).
- OOP improves maintenance: faulty module can be isolated (slide comparing procedural vs OOP service repair).
- Dot-notation and DOM manipulation showcase how browser objects themselves follow OOP principles.
- Static members illustrate class-wide data (e.g., global count of resources) – common in enterprise logging, configuration, or license tracking.
Key Takeaways for Exam Preparation
- Memorise OOP pillars: Abstraction, Encapsulation, Inheritance, Polymorphism.
- Understand JavaScript syntax for:
- Class declarations, constructors,
extends, super. - Public vs private fields (
#), static fields/methods, getter/setter patterns. - DOM object manipulation via dot notation.
- Practise turning real-world specs (car, phone) into classes, then instantiating & interacting through methods.
- Be ready to explain how exception handling and modularisation make programs more reliable.
- Revisit
Date object operations and array usage (switch, forEach) as auxiliary OOP demonstrations.