KotlinCS 124 LogoJava

Objects, Continued

class Dimensions(val width: Double, val height: Double) {
fun area(): Double {
return width * height
}
}
val room = Dimensions(8.8, 10.0)
println(room.area())

Next we continue our exploration of Kotlin objects. Objects combine state and behavior. Yesterday we showed how they can store data like variables. Now we’ll show how they can run algorithms like methods.

Debugging Challenge
Debugging Challenge

But let’s start with some debugging practice!

Object Methods
Object Methods

Yesterday we began experimenting with simple Kotlin objects. Consider an object that stores information about a room:

class Room(val width: Double, val height: Double, val name: String)

Our Room class allows us to model a Rooms height, width, and name. Let’s create a few instances!

class Room(val width: Double, val height: Double, val name: String)
val livingRoom = Room(10.0, 8.0, "Living Room")
val kitchen = Room(6.0, 12.0, "Kitchen")
println("The ${kitchen.name} is ${kitchen.width} by ${kitchen.height}")
println("The ${livingRoom.name} is ${livingRoom.width} by ${livingRoom.height}")

Cool! But we said that Kotlin objects combine state and behavior. Where’s the behavior?

To start, let’s see if we can have each room print out the String that we printed manually in the previous example. We’ll go through how to do that together.

class Room(val width: Double, val height: Double, val name: String)
val livingRoom = Room(10.0, 8.0, "Living Room")

Instance Methods
Instance Methods

What we’ve created above is called an instance method. In some ways it’s just like the other methods that we’ve written. But, because it is part of a class definition, it is also different.

Specifically, instance methods have access to the values of instance variables or properties. We saw that in the walkthrough above, since our print function could access that room’s width, height, and name. Let’s continue exploring this together, and look at how instance methods can both access instance variables and accept parameters.

class Room(val width: Double, val height: Double, val name: String)

Modifying Instance Variables
Modifying Instance Variables

Instance methods can both access and modify instance variables. Let’s look at example of how that works.

class Room(val width: Double, val height: Double, val name: String)

CS People: Marques Brownlee
CS People: Marques Brownlee

If you’ve ever found yourself searching for technology product reviews on YouTube, you may have already run across the work of Marques Brownlee. A YouTube technology reviewer with 16 million subscribers, Marques is also a high-level professional Ultimate frisbee player. In the video below he discusses some of the challenges with being a diverse individual in technology with another fairly well-known Black man, Barack Obama:

More Practice

Need more practice? Head over to the practice page.