In this section, we will have a quick look at how behaviors and functions can be implemented. We will continue with our Person class, which has three behaviors—speak, eat, and walk.
As we know, class behaviors are represented by functions. We can declare a function within the class body:
- Create a class with a primary constructor and add the speak() function by using fun keyword. When a function is declared in the class body, it becomes class behavior:
class Person (val name: String, var age : Int , var height : Double) {
fun speak() {
println("My name is $name , i am $age years old and I am $height feet tall")
}
}
fun main(args: Array<String>) {
val abid = Person("Abid", 40, 6.0)
abid.speak()
}
- Create an object of the Person class and call the speak function using the . operator. Execute this program and...