Skip to content

Abstraction

Last updated on March 22, 2024

Abstraction only exposes relevant data and method and hide the internal implementation. In Swift, this could mean using protocol.

Another way to illustrate this example is the analogy of the tip of the iceberg, you only care about the tip of the iceberg and you don’t really care about anything happening beneath the iceberg.

You will be using the same base code from What is Object-oriented programming and look into some of the example of abstraction.

Let’s create a protocol where you can define the animal’s action.

protocol AnimalAction {
  func play() -> String
}

And Animal class should conform to AnimalAction. Now, all the subclasses can then choose to override func play() -> String or use the default once which returns Roll on the floor.

class Animal: AnimalAction {
    let name: String
    let age: Int

    private var isFed: Bool = false

    init(name: String, age: Int) {
        self.name = name
        self.age = age
    }

    func play() -> String {
        return "Roll on the floor"
    }
}

There are some other subclasses like Dog, Cat and Bird that can choose to override it but for your case, you will only include it for Dog. You can define an action for dog playing which is jump jump jump in my case.

class Dog: Animal {
    override init(name: String, age: Int) {
        super.init(name: name, age: age)
    }

    override func makeSomeNoise() -> String {
        return "Barrkkk~"
    }

    override func play() -> String {
        return "Jump jump jump"
    }
}

If you recall, you have some dogs, cats and birds. Let’s see them all.

let popo = Dog(name: "Popo", age: 1)
let lolo = Dog(name: "Lolo", age: 3)

let birdy = Bird(name: "Birdy", age: 7)
let twitie = Bird(name: "Twitie", age: 4)

let dodo = Cat(name: "Dodo", age: 2)
let momo = Cat(name: "Momo", age: 4)

And when you instruct your animals to play, you’ll notice that the birds are having the same play motion as the cat because it’s using the default Roll on the floor. And it’s different for the dog because we override it.

popo.play() // Jump jump jump
lolo.play() // Jump jump jump

birdy.play() // Roll on the floor
twitie.play() // Roll on the floor

dodo.play() // Roll on the floor
momo.play() // Roll on the floor

Where to go From Here

Object-oriented programming is the most basic paradigm in terms of programming. Once you have graps the concept, you are good to go. Object-oriented programming is based on four pillars of concept that differentiate from other programming paradigms. Those fours are:

  1. Inheritance
  2. Polymorphism
  3. Encapsulation
  4. Abstraction
Published inDesign Pattern

Comments are closed.