Now that we’ve created our first class, let’s create an instance of it. An instance of a class resembles an object that is a member of that given class.
Recall the Car
class from the previous exercise:
class Car { val year = 2011 val model = "Jeep" val color = "Blue" }
To make an instance of this class, we’d utilize the following syntax:
val myCar = Car()
- We’ve declared the name of our instance/object to be
myCar
. This name is arbitrary and is up to the developer’s choosing. - Following the assignment operator, we’ve invoked the
Car
class with the name of the class followed by parentheses - the same syntax we use when invoking a function. - With this line of code, the
myCar
instance now possesses all the properties and their respective values that were specified within the class body.
Just like we’ve done with Kotlin’s built-in properties such as .length
and .size
, we can utilize the dot notation and append our class property names on our instance/object and retrieve their values.
println(myCar.year) // Prints: 2011 println(myCar.model) // Prints: Jeep println(myCar.color) // Prints: Blue
Voila! You’ve created your first object. Think about what you’ve learned about classes and their properties. What is one way that we might need to improve upon with this code? Follow the checkpoints below to find out.
Instructions
Within the main()
function of Building.kt, create an instance of the Building
class and assign it to the variable, residentialBuilding
.
Create three print statements that use dot notation to output each value of the instance, residentialBuilding
.
Optional:
If you create another instance of the Building
class, say commercialBuilding
, and output its property values, what do you expect to see?
Check the Hint for a clue.