Objects of a Class
In this lesson, you will create your first object of a class and learn how to set its fields and call its methods.
Instantiating a Class
Once a class has been defined, you can create objects from the class blueprint using the new
keyword followed by the class identifier.
We usually don’t create objects for the sake of just creating them, rather, we want to work with them in some way. For this reason, we assign the object to a variable. Let’s instantiate our Person
class.
For ease, the code for creating the class is also provided below.
class Person{var name: String = "temp"var gender: String = "temp"var age: Int = 0def walking = println(s"$name is walking")def talking = println(s"$name is talking")}// Creating an object of the Person classval firstPerson = new Person
Setting the Field Values
Now that we have our object firstPerson
, let’s set its field values. To do so, we call the field we wish to set on the object whose field we wish to set.
Let’s set the name
, gender
, and age
of ...