Welcome to our Kotlin tutorial on Classes and Objects! š
In this lesson, we'll explore the fundamental building blocks of Kotlin programming ā classes and objects. You'll learn how to create your own custom classes, understand the concept of objects, and see how they can be used in real-world projects.
Let's dive right in!
š” Pro Tip: A class is a blueprint for creating objects, while an object is an instance of a class that has its own properties and behaviors.
Classes are used to define a new type in Kotlin. They encapsulate data and behavior for a particular concept in your program.
class Car(val brand: String, val model: String, val year: Int) {
fun startEngine() {
println("Engine started!")
}
}In this example, Car is a class with three properties: brand, model, and year. The val keyword before a property indicates it's a read-only property. The startEngine() function is a method that defines some behavior for a Car object.
To create an object, simply provide a main method with a specific name (main by default) and call the class constructor.
fun main() {
val myCar = Car("Toyota", "Corolla", 2020)
myCar.startEngine() // Output: Engine started!
}In this example, myCar is an instance of the Car class, and we're calling the startEngine() method on that object.
š Note: By convention, objects in Kotlin have the same name as the class, and they are written in a single line of code, starting with lowercase and capitalizing the first letter of each new word. For example, val myCar = Car(...).
š” Pro Tip: A primary constructor is a constructor that is declared inside a class without explicit constructor syntax.
You can create a primary constructor to initialize the properties of a class during object creation.
class Person(val name: String, val age: Int) {
fun greet() {
println("Hello, I'm $name!")
}
}
fun main() {
val john = Person("John", 30)
john.greet() // Output: Hello, I'm John!
}š” Pro Tip: Access modifiers determine the visibility of properties and methods within a class and from outside the class.
You can control the visibility of class properties using access modifiers:
open: Allows subclasses to override the property or method.protected: Makes the property or method accessible within the same class and its subclasses.internal: Makes the property or method accessible within the same module.private: Makes the property or method accessible only within the same class.class MyClass {
private val privateProperty = "Private"
protected var protectedProperty = "Protected"
internal var internalProperty = "Internal"
var publicProperty = "Public"
}š” Pro Tip: Initializer blocks run after the constructor is called, and they are used to initialize properties.
Initializer blocks allow you to initialize properties in a separate block, which can be useful when you need to perform complex calculations or setup before constructing the object.
class Rectangle(val width: Int, val height: Int) {
init {
if (width <= 0 || height <= 0) {
throw IllegalArgumentException("Invalid dimensions for Rectangle.")
}
}
}š” Pro Tip: Kotlin objects are singleton instances of a class that are initialized only once per JVM.
You can create objects in Kotlin to represent a single instance of a class, which can be useful when working with global settings or utilities.
object Utility {
fun convertCelsiusToFahrenheit(celsius: Double): Double {
return (celsius * 9 / 5) + 32
}
}
fun main() {
println(Utility.convertCelsiusToFahrenheit(30.0)) // Output: 86.0
}That's it for our Kotlin Classes and Objects tutorial! š
In the next lesson, we'll dive deeper into Kotlin by exploring functions, control structures, and collections. Stay tuned!