Classes are fundamental building blocks in Kotlin, providing a blueprint for creating objects. They encapsulate data and behavior, promoting code organization and reusability.
In Kotlin, classes are declared using the class keyword. Here's a simple class declaration:
class Person {
var name: String = ""
var age: Int = 0
}
This creates a basic class named Person with two properties: name and age.
Kotlin classes can have a primary constructor and one or more secondary constructors. The primary constructor is part of the class header:
class Person(val name: String, var age: Int) {
// Class body
}
For more complex initialization logic, you can use an init block:
class Person(val name: String, var age: Int) {
init {
println("Person created: $name, $age years old")
}
}
Classes can contain properties (variables) and methods (functions). Here's an example:
class Person(val name: String, var age: Int) {
fun introduce() {
println("Hi, I'm $name and I'm $age years old.")
}
}
To create an object from a class, you use the class name followed by parentheses:
val john = Person("John Doe", 30)
john.introduce() // Output: Hi, I'm John Doe and I'm 30 years old.
Kotlin provides visibility modifiers to control access to class members:
public (default): Visible everywhereprivate: Visible inside the class onlyprotected: Visible in the class and its subclassesinternal: Visible inside the same moduleKotlin classes are final by default. To allow inheritance, use the open keyword:
open class Animal(val name: String) {
open fun makeSound() {
println("The animal makes a sound")
}
}
class Dog(name: String) : Animal(name) {
override fun makeSound() {
println("The dog barks")
}
}
For more advanced class features, explore Kotlin Inheritance and Kotlin Interfaces.
Classes form the backbone of object-oriented programming in Kotlin. They provide a powerful way to structure your code and model real-world entities in your programs.
To dive deeper into Kotlin's object-oriented features, check out Kotlin Objects and Kotlin Constructors.