Kotlin Overriding Properties 🎯

beginner
14 min

Kotlin Overriding Properties 🎯

Welcome back to CodeYourCraft! Today, we're diving into the exciting world of Kotlin and exploring a powerful feature: Overriding Properties. Let's get started!

What are Properties? 📝

Properties in Kotlin are like fields with built-in getters and setters. They provide a convenient way to access and modify an object's state.

kotlin
class Person(var name: String, var age: Int) val person = Person("John Doe", 30) println(person.name) // Output: John Doe person.name = "Jane Doe" println(person.name) // Output: Jane Doe

In the example above, we have a Person class with two properties: name and age. We can easily access and modify these properties using the dot notation.

Overriding Properties 💡

Sometimes, we might want to customize how a property behaves in a subclass. This is where overriding properties comes in handy! Let's create a subclass Employee and override the age property.

kotlin
class Person(var name: String, var age: Int) class Employee(name: String, override var age: Int) : Person(name, age) val employee = Employee("John Doe", 30) println(employee.age) // Output: 30 employee.age = 31 println(employee.age) // Output: 31

In the Employee class, we've marked the age property with the override keyword, which means we're replacing the original age property from the Person class.

Customizing Getters and Setters 💡

We can also customize the behavior of getters and setters by providing custom implementations for them.

kotlin
class Person(var name: String, var age: Int) { val fullAge: Int get() = if (age >= 18) age else age + 18 } val person = Person("John Doe", 16) println(person.fullAge) // Output: 34

In this example, we've created a fullAge property that returns the person's actual age if they're over 18, or their age plus 18 if they're under 18.

Quiz Time 🎯

Quick Quiz
Question 1 of 1

What does the `override` keyword do in Kotlin?

That's it for today's lesson on overriding properties in Kotlin! We've learned how to override properties in a subclass and customize getters and setters.

In the next lesson, we'll dive deeper into more advanced Kotlin concepts. Until then, happy coding! 🚀