Hello! Today, we'll reinforce our understanding of Object-Oriented Programming (OOP) in Kotlin by revisiting the concepts of Encapsulation, Abstraction, Inheritance, and Polymorphism. Let's dive in!
We'll delve back into OOP. As you may recall, we create objects from classes, which define properties (data) and methods (operations). Also, keep in mind that the keyword this
refers to the object whose methods and properties are being accessed.
Here's a refresher:
Kotlin1class Person { 2 var name: String = "" 3 fun introduce() { 4 // Implicitly, "this" references the "name" of the current Person object. 5 println("Hello, my name is $name.") 6 } 7}
Now, let's revisit the core principles of OOP: Encapsulation, Abstraction, Inheritance, and Polymorphism.
Encapsulation protects data by making properties private and providing safe methods for access.
Abstraction simplifies systems by creating higher-level representations.
Inheritance allows classes to share properties and methods, promoting code reusability.
Polymorphism enables different types of objects to be handled uniformly if they share some features.
Below is an example demonstrating polymorphism and inheritance:
Kotlin1open class Animal { 2 open fun makeSound() { 3 println("The animal makes a sound") 4 } 5} 6 7class Pig : Animal() { 8 override fun makeSound() { 9 println("Oink! Oink!") 10 } 11}
In this example, Pig
, a subclass of Animal
, overrides the makeSound
method, showcasing polymorphism.
To solidify our understanding, let's examine some practical Kotlin examples.
First, an Employee
class showcases encapsulation:
Kotlin1class Employee(private var name: String, private var salary: Double) { 2 fun getName(): String { 3 // getName provides safe access to the name property 4 return name 5 } 6 7 fun getSalary(): Double { 8 // Similarly, getSalary provides safe access to the salary property 9 return salary 10 } 11 12 fun raiseSalary(percent: Double) { 13 if (percent > 0) { 14 // We can safely modify the private salary property within the class 15 salary += salary * percent / 100.0 16 } 17 } 18}
An interface is used to illustrate abstraction:
Kotlin1interface Drawable { 2 fun draw() 3} 4 5class Circle(private val radius: Double) : Drawable { 6 override fun draw() { 7 // Circle implements the abstract requirement of the Drawable interface 8 println("Drawing a Circle with a radius of $radius") 9 } 10}
To sum up, we've reviewed the implementation of the four pillars of OOP in Kotlin — encapsulation, abstraction, inheritance, and polymorphism — and observed these principles in action through demonstrative examples. Our next step is applying this knowledge in the practice session. Happy coding!