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!
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.
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 DoeIn 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.
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.
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: 31In 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.
We can also customize the behavior of getters and setters by providing custom implementations for them.
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: 34In 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.
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! 🚀