Menu
Coddy logo textTech

Defining Classes

Part of the Object Oriented Programming section of Coddy's Kotlin journey. Lesson 2 of 57.

A class describes a kind of object: the data it holds and what it can do. class Dog { ... } declares the type, and Dog() creates an object of that type, an instance. Kotlin has no new keyword:

class Dog {
    var name = "Rex"
    var age = 3
}

Inside main:

val dog = Dog()
println(dog.name)
println(dog.age)

Output:

Rex
3

The variables inside a class are its properties. Every instance has its own copy, read and changed with a dot:

class Dog {
    var name = "Rex"
}

Inside main:

val first = Dog()
val second = Dog()
second.name = "Bella"
println(first.name)
println(second.name)

Output:

Rex
Bella

A function inside a class is a method (Kotlin calls them member functions). A method can read and change the properties of the instance it is called on:

class Counter {
    var count = 0

    fun increment() {
        count++
    }

    fun report() = "count is $count"
}

Inside main:

val clicks = Counter()
clicks.increment()
clicks.increment()
println(clicks.report())

Output:

count is 2

Class names use UpperCamelCase (BankAccount); properties and methods use lowerCamelCase (balance, deposit()). Grouping the data with the functions that work on it is the core idea of object-oriented programming: code that uses a Counter calls increment() and never needs to know how the count is stored.

class BankAccount {
    var balance = 0

    fun deposit(amount: Int) {
        balance += amount
    }
}
challenge icon

Challenge

Easy

Complete the method describe() of the class Pet. It returns one sentence built from the properties: a pet named Rex, species dog, age 3 gives Rex is a 3 year old dog.

The supplied code creates a Pet, sets its properties from the input (name, species, age) and prints the result of describe().

Your code goes in Pet.kt. Main.kt holds the supplied input/output code and cannot be edited.

Try it yourself

fun main() {
    // Supplied input/output code: keep it as it is
    val input = generateSequence(::readLine).toList()
    val pet = Pet()
    pet.name = input[0]
    pet.species = input[1]
    pet.age = input[2].toInt()
    println(pet.describe())
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Object Oriented Programming

Practice on your own: Kotlin playground