Table of contents
No headings in the article.
This article will introduce you to the concept of object-oriented programming in a simpler way. So let's dive right in. Procedural programming is quite different from object-oriented programming in that it entails writing methods that perform operations on the data whereas object-oriented programming is a technique used to break down problems into smaller bits by creating objects. Objects contain both data and methods. In OOP, we structure a software program into a simple reusable piece of code blueprints usually called classes, which are used to create individual instances of objects. Objects have state and behavior.
Object-oriented programming has several advantages over procedural programming in that:
- OOP is easier to execute.
- OOP creates a clear structure for the programs.
- OOP helps to keep the Kotlin code DRY "Don't Repeat Yourself", and makes the code easier to maintain, modify and debug.
- OOP makes it possible to create full reusable applications with less code and shorter development time.
This brings us to another question. What are classes? A class is a blueprint that is used to create more specific objects. Let us take the case of an architect.
An architect has a blueprint for what he wants a building to look like. From that blueprint, multiple buildings can be built. Each of the buildings can have a unique name and properties, but they all share the same fundamental features. Below is how you create a class;
class Car(var make: String, var model: String, var registration: String, var speed: Int) { public fun start() { println("I am starting") } public fun accelerate(acceleration: Int): Int { speed = speed + acceleration return speed } } fun main() { var gari = Car("Nissan", "Leaf", "KDA 379G", 0) gari.start() println(gari.speed) gari.accelerate(30) println(gari.speed) }
A class is created using the keyword. Next, we have the class name and parameters that make up its primary constructor. A class may be class created without parameters in the primary constructor. If parameters are specified, they must be provided when creating an instance of the class. The body of the class is demarcated by a pair opening and closing curly braces. { } From the Car class, we are able to create an object and assign it to a variable. We access the object’s properties (state) and functions gari.We access the object's properties and behaviors using the dot notation.e.g println(gari.registration) //prints out KDA 397G
OOP has 4 principles which include:
- Inheritance
- Encapsulation
- Abstraction
- Polymorphism