Hello and welcome! In this lesson, we'll dive into Object-Oriented Programming (OOP). Object-Oriented Programming is a coding paradigm inspired by the real world. It envisages everything as an "Object" with certain properties (characteristics) and capabilities (methods). Take a football as an instance: it has properties like size and color and methods such as being able to be kicked or caught.
A Class in Kotlin serves as a blueprint for creating objects. Using a Class, we essentially instruct Kotlin on the appearance and function of an object. We can declare a Class using the class
keyword.
In this Class, we also define properties (characteristics) and methods (actions) that our object can have and perform. Check out this simple Football
Class:
Kotlin1class Football { 2 val color: String = "brown" // property 1 3 var size: Int = 5 // property 2 4 fun kick() { // method 5 println("The football has been kicked") 6 } 7}
An Object is a specific instance of a Class, built according to the blueprint we defined. To create an Object in Kotlin, we simply call the Class name:
Kotlin1val myFootball = Football()
So now, myFootball
is an Object of the Football
Class, possessing the properties and methods we defined in the Football
Class.
Once we've created an Object, we can interact with it, accessing its properties and invoking its methods using the dot operator .
.
For instance, to access the color
property of the myFootball
object, we write:
Kotlin1println(myFootball.color) // prints 'brown'
And to invoke the kick
method of the myFootball
object, we use:
Kotlin1myFootball.kick() // prints 'The football has been kicked'
This approach enables us to interact with digital objects in a manner similar to how we interact with real-world objects!
Congratulations on completing your first foray into Kotlin and OOP! You've learned about Kotlin Classes and Objects, and how to interact with them!
Ensure to practice by creating your own classes and objects, thereby solidifying your understanding. The upcoming exercises will provide ample opportunities for you to flex your OOP muscles, so keep coding, and we'll see you in the next lesson!