Sobes.tech
Intern

Mis on objektorienteeritud programmeerimine?

sobes.tech AI

Vastus AI-lt

Object-oriented programming (OOP) is a programming paradigm built around the concept of "objects," which can contain data (attributes) and code (methods).

The main principles of OOP include:

  • Encapsulation: Hiding data and methods within an object, which are accessed through a well-defined interface.
  • Inheritance: A mechanism that allows one class (child) to inherit properties and behaviors from another class (parent).
  • Polymorphism: The ability to use the same interface for objects of different classes, with each object behaving in its own way.
// Example of encapsulation in Swift
struct Point {
    private var x: Double
    private var y: Double

    init(x: Double, y: Double) {
        self.x = x
        self.y = y
    }

    func distance(to otherPoint: Point) -> Double {
        let deltaX = self.x - otherPoint.x
        let deltaY = self.y - otherPoint.y
        return sqrt(deltaX * deltaX + deltaY * deltaY)
    }
}

let p1 = Point(x: 0, y: 0)
let p2 = Point(x: 3, y: 4)
// print(p1.x) // Compilation error: 'x' is inaccessible due to 'private' protection level
print(p1.distance(to: p2)) // Output: 5.0
// Example of inheritance in Swift
class Animal {
    func speak() {
        print("Some generic sound")
    }
}

class Dog: Animal {
    override func speak() {
        print("Woof!")
    }
}

let myDog = Dog()
myDog.speak() // Output: Woof!
// Example of polymorphism in Swift

// Using the classes Animal and Dog from the inheritance example

func makeAnimalSpeak(animal: Animal) {
    animal.speak()
}

let someAnimal: Animal = Animal()
let aDog: Animal = Dog() // Dog object, but considered as Animal

makeAnimalSpeak(animal: someAnimal) // Output: Some generic sound
makeAnimalSpeak(animal: aDog) // Output: Woof!

Advantages of OOP:

  • Code reuse: Through inheritance and composition.
  • Improved readability and maintainability: Code is organized into logical units (objects).
  • Flexibility: Polymorphism allows easy addition of new object types without changing existing code.
  • Easier debugging: It allows isolating problems within specific objects.