In Kotlin, classes and objects are fundamental concepts in Object-Oriented Programming (OOP). They allow developers to model real-world entities and behaviors within software applications, promoting code reuse, modularity, and maintainability.
Classes and objects enable developers to:
Class: A class is a blueprint or template for creating objects. It defines the properties (attributes) and behaviors (methods) that the objects instantiated from it will have.
Object: An object is an instance of a class. It contains specific data and can perform the behaviors defined by its class.
In Kotlin, a class is declared using the class keyword:
class Car(val make: String, val model: String, val year: Int) {
fun startEngine() {
println("The engine of $make $model is now running.")
}
}
An object is created by calling the class constructor:
val myCar = Car("Toyota", "Corolla", 2022)
myCar.startEngine()
public, private, protected, and internal modifiers.class Car(val make: String, val model: String, val year: Int) {
fun startEngine() {
println("The engine of $make $model is now running.")
}
}
class Car(val make: String, val model: String) {
val year: Int
constructor(make: String, model: String, year: Int) : this(make, model) {
this.year = year
}
fun startEngine() {
println("The engine of $make $model is now running.")
}
}
class Car(val make: String, val model: String, val year: Int) {
init {
println("Car initialized: $make $model, $year")
}
fun startEngine() {
println("The engine of $make $model is now running.")
}
}
public, private, protected, and internal modifiers.init block? The init block allows for additional initialization logic during object creation.| Feature | Primary Constructor | Secondary Constructor | Init Block |
|---|---|---|---|
| Declared In | Class Header | Class Body | Class Body |
| Purpose | Initialize Class Properties | Provide Additional Initialization Logic | Execute Additional Setup During Object Initialization |
| Usage | Simple Initialization | Complex Initialization | Additional Setup |
fun main() {
val myCar = Car("Toyota", "Corolla", 2022)
myCar.startEngine()
}
Output:
Car initialized: Toyota Corolla, 2022
The engine of Toyota Corolla is now running.