Welcome to The Coding College! In this tutorial, we’ll explore classes and objects in Kotlin—key components of Object-Oriented Programming (OOP). Understanding these concepts is crucial for building reusable and maintainable applications.
What Are Classes and Objects?
- Class: A blueprint or template that defines the properties and behaviors (methods) of an object.
- Object: An instance of a class that holds real data and interacts with other objects.
Syntax of a Kotlin Class
class ClassName {
// Properties (variables)
// Methods (functions)
}
Example:
class Car {
var brand: String = ""
var model: String = ""
var year: Int = 0
fun displayInfo() {
println("Car: $brand $model ($year)")
}
}
fun main() {
val car = Car()
car.brand = "Tesla"
car.model = "Model 3"
car.year = 2024
car.displayInfo()
}
// Output: Car: Tesla Model 3 (2024)
Objects in Kotlin
An object is created using the val
or var
keyword and the ClassName()
constructor.
Example:
val car = Car()
Primary Constructor
The primary constructor is defined in the class header and is used to initialize properties.
Example:
class Person(val name: String, val age: Int)
fun main() {
val person = Person("Naman", 24)
println("Name: ${person.name}, Age: ${person.age}")
}
// Output: Name: Naman, Age: 24
Secondary Constructor
A secondary constructor allows for additional initialization logic.
Example:
class Animal {
var name: String
var age: Int
constructor(name: String, age: Int) {
this.name = name
this.age = age
}
fun displayInfo() {
println("Animal: $name, Age: $age")
}
}
fun main() {
val animal = Animal("Dog", 5)
animal.displayInfo()
}
// Output: Animal: Dog, Age: 5
Initializer Block (init
)
The init
block is executed when an object is created, ideal for performing initialization tasks.
Example:
class Laptop(val brand: String, val price: Int) {
init {
println("Laptop: $brand, Price: $$price")
}
}
fun main() {
val laptop = Laptop("Dell", 800)
}
// Output: Laptop: Dell, Price: $800
Class Properties
Properties are variables defined in a class. They can be mutable (var
) or immutable (val
).
Example:
class Book(val title: String, var price: Double)
fun main() {
val book = Book("Kotlin Essentials", 29.99)
println("Title: ${book.title}, Price: $${book.price}")
book.price = 24.99
println("Updated Price: $${book.price}")
}
// Output:
// Title: Kotlin Essentials, Price: $29.99
// Updated Price: $24.99
Methods in Classes
Methods are functions defined inside a class to perform specific tasks.
Example:
class Calculator {
fun add(a: Int, b: Int): Int {
return a + b
}
}
fun main() {
val calculator = Calculator()
println("Sum: ${calculator.add(10, 5)}")
}
// Output: Sum: 15
Nested and Inner Classes
1. Nested Class
A class defined inside another class. It does not have access to the outer class’s properties.
Example:
class Outer {
class Nested {
fun greet() = "Hello from Nested Class"
}
}
fun main() {
val nested = Outer.Nested()
println(nested.greet())
}
// Output: Hello from Nested Class
2. Inner Class
An inner class has access to the outer class’s properties.
Example:
class Outer {
val name = "Outer"
inner class Inner {
fun greet() = "Hello from Inner Class of $name"
}
}
fun main() {
val inner = Outer().Inner()
println(inner.greet())
}
// Output: Hello from Inner Class of Outer
Singleton Object
In Kotlin, you can create a singleton object using the object
keyword.
Example:
object Database {
val name = "MyDatabase"
fun connect() {
println("Connecting to $name")
}
}
fun main() {
Database.connect()
}
// Output: Connecting to MyDatabase
Companion Object
A companion object is used to define static members in a class.
Example:
class Utils {
companion object {
fun greet(name: String) {
println("Hello, $name!")
}
}
}
fun main() {
Utils.greet("Naman")
}
// Output: Hello, Naman!
Why Learn Classes and Objects with The Coding College?
At The Coding College, we make learning Kotlin simple and practical. With detailed explanations and real-world examples, our tutorials help you gain the confidence to build robust applications using Kotlin.
Conclusion
Understanding classes and objects is fundamental to mastering Kotlin and Object-Oriented Programming. These concepts allow you to create reusable, organized, and scalable code.