Skip to main content

Kotlin Classes Basics

Classes are the foundation of object-oriented programming in Kotlin. They serve as blueprints for creating objects, which combine data and behavior in a single unit. In this tutorial, we'll explore the basics of Kotlin classes, including how to define them, create objects, work with properties, and understand constructors.

What Are Classes?

In Kotlin, a class is a blueprint that defines the structure and behavior of objects. Think of a class as a template that describes:

  • What data the object will store (properties)
  • What actions the object can perform (methods)
  • How the object is created (constructors)

Defining Your First Class

Let's start with a simple class definition:

kotlin
class Person {
// Class body
}

This creates a basic class named Person. Even this minimal class definition is useful - Kotlin automatically provides:

  • A default constructor with no parameters
  • Memory allocation for creating instances
  • Basic functions like toString(), equals(), and hashCode()

Creating Objects (Instances)

Once you've defined a class, you can create objects (instances) of that class:

kotlin
fun main() {
val person1 = Person() // Creates a new Person instance
val person2 = Person() // Creates another Person instance

println(person1)
println(person2)
}

Output:

Person@1a407d53
Person@3d8c7aca

Notice that Kotlin doesn't use the new keyword for object creation, unlike Java or C#.

Adding Properties to a Class

Properties represent the data each object will store:

kotlin
class Person {
var name: String = "Unknown"
var age: Int = 0
}

fun main() {
val person = Person()

// Accessing properties
println("Default name: ${person.name}")
println("Default age: ${person.age}")

// Modifying properties
person.name = "Alice"
person.age = 25

println("Updated name: ${person.name}")
println("Updated age: ${person.age}")
}

Output:

Default name: Unknown
Default age: 0
Updated name: Alice
Updated age: 25

Property Types in Kotlin

In Kotlin, properties can be:

  1. Mutable (var): Can be changed after initialization
  2. Immutable (val): Can only be assigned once
kotlin
class User {
val id: Int = 1 // Read-only property (cannot be changed)
var username: String = "" // Mutable property (can be changed)
}

Constructors

Constructors are special methods used to initialize objects when they're created. Kotlin has two types of constructors:

Primary Constructor

The primary constructor is part of the class header:

kotlin
class Person(val name: String, var age: Int) {
// Class body
}

fun main() {
val person = Person("Bob", 30)
println("Name: ${person.name}, Age: ${person.age}")

// We can change age because it's a var
person.age = 31
// We can't change name because it's a val
// person.name = "Robert" // This would cause a compilation error

println("Updated age: ${person.age}")
}

Output:

Name: Bob, Age: 30
Updated age: 31

Notice how parameters in the primary constructor can become properties by using val or var.

Initialization Blocks

You can add initialization code using init blocks:

kotlin
class Person(val name: String, var age: Int) {

init {
println("Person created with name: $name")

// Validate age
require(age >= 0) { "Age cannot be negative" }
}
}

fun main() {
val person = Person("Charlie", 25)
// This would throw an exception: val invalid = Person("Invalid", -1)
}

Output:

Person created with name: Charlie

Secondary Constructors

You can define additional constructors if needed:

kotlin
class Person(val name: String, var age: Int) {

var email: String = ""

// Secondary constructor
constructor(name: String, age: Int, email: String) : this(name, age) {
this.email = email
}
}

fun main() {
val person1 = Person("Dave", 40)
val person2 = Person("Emma", 35, "[email protected]")

println("Person 1: ${person1.name}, ${person1.age}, ${person1.email}")
println("Person 2: ${person2.name}, ${person2.age}, ${person2.email}")
}

Output:

Person 1: Dave, 40, 
Person 2: Emma, 35, [email protected]

Member Functions

Classes can contain functions (methods) that represent the behaviors of objects:

kotlin
class Person(val name: String, var age: Int) {

fun introduce() {
println("Hi, I'm $name and I'm $age years old")
}

fun celebrateBirthday() {
age++
println("$name just turned $age")
}
}

fun main() {
val person = Person("Frank", 45)
person.introduce()
person.celebrateBirthday()
}

Output:

Hi, I'm Frank and I'm 45 years old
Frank just turned 46

Real-World Example: Creating a Book Class

Let's create a practical example of a Book class that might be used in a digital library system:

kotlin
class Book(
val title: String,
val author: String,
val year: Int,
val isbn: String,
var available: Boolean = true
) {
// Track number of times this book was borrowed
private var borrowCount: Int = 0

fun borrow(): Boolean {
if (available) {
available = false
borrowCount++
println("\"$title\" has been borrowed")
return true
}
println("Sorry, \"$title\" is not available")
return false
}

fun returnBook() {
if (!available) {
available = true
println("\"$title\" has been returned")
} else {
println("This book wasn't borrowed")
}
}

fun displayInfo() {
println("Book: \"$title\"")
println("Author: $author")
println("Year: $year")
println("ISBN: $isbn")
println("Available: ${if(available) "Yes" else "No"}")
println("Times borrowed: $borrowCount")
}
}

fun main() {
// Create a few books
val book1 = Book("The Great Gatsby", "F. Scott Fitzgerald", 1925, "978-3-16-148410-0")
val book2 = Book("Moby Dick", "Herman Melville", 1851, "978-1-23-456789-7")

// Display initial info
book1.displayInfo()
println()

// Borrow and return books
book1.borrow()
book2.borrow()
println()

book1.displayInfo()
println()

book1.returnBook()
book1.borrow()
book1.returnBook()
println()

// Display final state
book1.displayInfo()
}

Output:

Book: "The Great Gatsby"
Author: F. Scott Fitzgerald
Year: 1925
ISBN: 978-3-16-148410-0
Available: Yes
Times borrowed: 0

"The Great Gatsby" has been borrowed
"Moby Dick" has been borrowed

Book: "The Great Gatsby"
Author: F. Scott Fitzgerald
Year: 1925
ISBN: 978-3-16-148410-0
Available: No
Times borrowed: 1

"The Great Gatsby" has been returned
"The Great Gatsby" has been borrowed
"The Great Gatsby" has been returned

Book: "The Great Gatsby"
Author: F. Scott Fitzgerald
Year: 1925
ISBN: 978-3-16-148410-0
Available: Yes
Times borrowed: 2

Summary

In this tutorial, you've learned the basics of Kotlin classes:

  • How to define classes and create objects
  • Working with properties (both mutable and immutable)
  • Using primary and secondary constructors
  • Adding initialization blocks
  • Creating member functions
  • A practical example of using classes in a real-world application

Classes are a fundamental building block in Kotlin and object-oriented programming. As you continue your journey, you'll learn more advanced concepts like inheritance, interfaces, and abstract classes that build upon these basics.

Exercises

  1. Create a Rectangle class with properties for width and height. Add methods to calculate area and perimeter.

  2. Design a BankAccount class with properties for account number, owner name, and balance. Add methods for deposit and withdrawal with appropriate validations.

  3. Implement a Student class with properties for name, ID, and a list of grades. Include methods to add grades and calculate the average grade.

Additional Resources

Happy coding with Kotlin classes!



If you spot any mistakes on this website, please let me know at [email protected]. I’d greatly appreciate your feedback! :)