Now let’s practice writing our own classes. A Kotlin class is declared at the top of a Kotlin file, outside the main()
function, with the class
keyword followed by its name:
class Name {
// class body
}
The name of a class should always start with an upper case letter and use the camel case form. The class body is contained within curly braces and will hold all of the properties and functions related to that class. We will take a closer look at class functions in a later exercise.
Note: It is optional for a Kotlin class to contain a body, thus if the class has no body, we can omit its curly braces, resulting in the following declaration:
class Name
Let’s revisit our real-world, Car
example. Suppose we create the following class:
class Car
Our blueprint is complete! But it’s not of much use to us empty. Any car possesses several properties including the year it was made, its model name, and color. Let’s add these:
class Car { val year = 2011 val model = "Jeep" val color = "Blue" }
We’ve created the properties, year
, model
, and color
and initialized them with values. Now any time we create a car object from this class, it will possess the properties, year
, model
and color
and hold their respective values. In the next exercise, we’ll learn how to create objects from a class. For now, let’s practice with the Kotlin class syntax. 🚗
Instructions
In Book.kt, declare an empty class called Book
.
Add the following properties and the values they hold:
pages
with the value,320
title
with the value,"Harry Potter and the Sorcerer's Stone"
author
with the value,"J.K. Rowling"