Kotlin Classes and Objects

beginner
13 min

Kotlin Classes and Objects

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!

What are classes and objects in Kotlin?

šŸ’” 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 in Kotlin

Classes are used to define a new type in Kotlin. They encapsulate data and behavior for a particular concept in your program.

kotlin
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.

Objects in Kotlin

To create an object, simply provide a main method with a specific name (main by default) and call the class constructor.

kotlin
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(...).

Creating classes with primary constructors

šŸ’” 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.

kotlin
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! }

Class properties and access modifiers

šŸ’” 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:

  1. open: Allows subclasses to override the property or method.
  2. protected: Makes the property or method accessible within the same class and its subclasses.
  3. internal: Makes the property or method accessible within the same module.
  4. private: Makes the property or method accessible only within the same class.
kotlin
class MyClass { private val privateProperty = "Private" protected var protectedProperty = "Protected" internal var internalProperty = "Internal" var publicProperty = "Public" }

Constructors and initializer blocks

šŸ’” 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.

kotlin
class Rectangle(val width: Int, val height: Int) { init { if (width <= 0 || height <= 0) { throw IllegalArgumentException("Invalid dimensions for Rectangle.") } } }

Kotlin objects

šŸ’” 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.

kotlin
object Utility { fun convertCelsiusToFahrenheit(celsius: Double): Double { return (celsius * 9 / 5) + 32 } } fun main() { println(Utility.convertCelsiusToFahrenheit(30.0)) // Output: 86.0 }

Quiz

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!