Sobes.tech
Intern

What is object-oriented programming (OOP)?

sobes.tech AI

Answer from AI

Object-oriented programming (OOP) is a programming paradigm based on the concept of "objects," which contain data (attributes) and methods (functions) that operate on this data.

Main principles of OOP:

  1. Encapsulation: Combining data and methods into a single unit (object) and hiding implementation details from the outside environment. Access to data is only through defined methods.
  2. Inheritance: Creating new classes (child classes) based on existing ones (parent classes), inheriting their attributes and methods. It allows reusing code and creating class hierarchies.
  3. Polymorphism: The ability of objects of different classes to respond differently to the same call. Implemented through method overriding or using protocols (interfaces).

Example in Swift:

// Example of encapsulation and a base class
class Car {
    private var speed: Double // Private property (encapsulation)

    init(initialSpeed: Double) {
        self.speed = initialSpeed
    }

    func accelerate(by factor: Double) {
        speed *= factor // Method to access private property
    }

    func getCurrentSpeed() -> Double {
        return speed
    }
}

// Example of inheritance
class ElectricCar: Car {
    var batteryLevel: Double

    init(initialSpeed: Double, initialBatteryLevel: Double) {
        self.batteryLevel = initialBatteryLevel
        super.init(initialSpeed: initialSpeed) // Call to parent class initializer
    }

    // Example of polymorphism (method overriding)
    override func accelerate(by factor: Double) {
        if batteryLevel > 10 { // Additional logic
            super.accelerate(by: factor * 1.1) // Call to parent method with modifier
            batteryLevel -= 5
        } else {
            print("Low battery, cannot accelerate much.")
        }
    }
}

// Example of polymorphism (usage)
let myCar: Car = Car(initialSpeed: 50)
let myElectricCar: Car = ElectricCar(initialSpeed: 60, initialBatteryLevel: 100)

// Although both variables are of type Car,
// calling accelerate() on myElectricCar will invoke the overridden method
myCar.accelerate(by: 1.5)
myElectricCar.accelerate(by: 1.5)
What is object-oriented programming (OOP)? — iOS - sobes.tech