OOPJuniorMCQ

What are the four pillars of Object-Oriented Programming?

Test your knowledge:

Explanation & Code

Answer: Encapsulation, abstraction, inheritance, and polymorphism. Swift supports all four, though it leans on protocols and value types more than classic class-based OOP languages.

PillarWhat it meansSwift example
EncapsulationHide internal state, expose controlled accessprivate(set) var balance
AbstractionExpose what something does, not howprotocol PaymentProcessor
InheritanceReuse/extend behavior from a base typeclass SavingsAccount: Account
PolymorphismSame interface, different underlying behavior[PaymentProcessor] holding multiple conforming types
protocol PaymentProcessor {
    func charge(_ amount: Decimal) -> Bool
}

class CreditCardProcessor: PaymentProcessor {
    func charge(_ amount: Decimal) -> Bool { /* ... */ true }
}

class PayPalProcessor: PaymentProcessor {
    func charge(_ amount: Decimal) -> Bool { /* ... */ true }
}

let processors: [PaymentProcessor] = [CreditCardProcessor(), PayPalProcessor()]
processors.forEach { _ = $0.charge(9.99) } // polymorphic dispatch

Rate your understanding:

Related Questions

Browse all OOP questions

Ready to practice more OOP?

Test yourself with our interactive quiz mode or browse all curated questions for this topic.