Member-only story

OOP Concepts

1. Classes and Objects

  • Class: A blueprint for creating objects. Defines properties and methods.
  • Object: An instance of a class.
Class                  Object
----- ------
Vehicle ------> myCar: Vehicle
- make - make: "Toyota"
- model - model: "Camry"
- year - year: 2021
- getDetails() - getDetails()

Swift Example:

class Vehicle {
var make: String
var model: String
var year: Int

init(make: String, model: String, year: Int) {
self.make = make
self.model = model
self.year = year
}
func getDetails() -> String {
return "\(year) \(make) \(model)"
}
}
let myCar = Vehicle(make: "Toyota", model: "Camry", year: 2021)
print(myCar.getDetails()) // Output: 2021 Toyota Camry

2. Encapsulation

  • Encapsulation: Bundling data (attributes) and methods that operate on the data into a single unit (class), and restricting direct access to some of the object’s components.
+---------------------------+
| Vehicle |
| +---------------------+ |
| | Private: | |
| | - make | |
| | - model | |
| | - year | |
| +---------------------+ |
| | Public: | |
| | - getDetails() | |
+---------------------------+

--

--

No responses yet