Welcome to this comprehensive guide on Kotlin Object-Oriented Programming (OOP)! This tutorial is designed to help you prepare for interviews, with a focus on beginners and intermediate level questions. Let's dive right in!
OOP is a programming paradigm that uses objects to represent data and methods. It encourages modular programming, which makes code easier to manage, test, and reuse.
Let's create a Car class with properties for brand and color, and a method to display the car details.
class Car(val brand: String, val color: String) {
fun displayDetails() {
println("Brand: $brand, Color: $color")
}
}val is used for immutable properties (values that cannot be changed once set).var is used for mutable properties (values that can be changed).displayDetails method prints the car details when called.Inheritance allows one class to acquire the properties and methods of another. The class that inherits is called the subclass or derived class, and the class being inherited from is called the superclass or base class.
class Sedan(brand: String, color: String) : Car(brand, color) {
val seats = 4
}In this example, Sedan inherits from Car. Every Sedan object automatically has a brand, color, and the ability to display details. Plus, it has an additional property seats.
Polymorphism is the ability of an object to take on many forms. It allows us to treat objects differently based on their types.
fun printVehicleDetails(vehicle: Vehicle) {
vehicle.displayDetails()
}
class Car(brand: String, color: String) : Vehicle(brand, color) {
// ...
}
class Bike(brand: String, color: String) : Vehicle(brand, color) {
// ...
}
val myCar = Car("Toyota", "Red")
val myBike = Bike("Honda", "Blue")
printVehicleDetails(myCar)
printVehicleDetails(myBike)In this example, we have a Vehicle class and two subclasses: Car and Bike. Both Car and Bike inherit the displayDetails method from Vehicle. We can pass a Car or a Bike object to the printVehicleDetails function, and it will correctly display the details for each object.
Which keyword in Kotlin is used to define immutable properties?
Happy coding! Stay tuned for more advanced Kotlin topics! 😄