So far, our classes have only contained data (properties). But in Object-Oriented Programming, objects should also have behavior.
You add behavior to a class by defining functions inside it. Functions defined inside a class are often called methods.
Defining a function inside a class is identical to defining a regular function. You use the fun keyword.
Because the function belongs to the class, it can easily access all the properties of that specific class without needing them passed as arguments!
class Car(var brand: String, var model: String) {
// A class function
fun drive() {
println("Vroom! The car is driving.")
}
}
fun main() {
val myCar = Car("Ford", "Mustang")
// Calling the class function using the dot operator
myCar.drive()
}
The true power of class functions is that they interact directly with the object's properties.
Let's create a Person class. We will add a function introduce() that prints a personalized greeting using the object's unique name and age properties.
class Person(var name: String, var age: Int) {
fun introduce() {
println("Hi, my name is $name and I am $age years old.")
}
}
fun main() {
val p1 = Person("Alice", 25)
val p2 = Person("Bob", 30)
// Each object uses its own data when calling the function!
p1.introduce()
p2.introduce()
}
Notice how p1.introduce() prints Alice's data, while p2.introduce() prints Bob's data. The function is the same, but the data context changes depending on which object is calling it!
Class functions can also take parameters and return values, exactly like regular functions.
Let's create a BankAccount class. It will have a function deposit() that takes an amount as a parameter, adds it to the balance, and returns the new total balance.
class BankAccount(var owner: String, var balance: Double) {
// Takes a Double parameter and returns a Double
fun deposit(amount: Double): Double {
balance += amount // Updates the class property
println("$owner deposited $$amount.")
return balance
}
}
fun main() {
val account = BankAccount("John", 100.0)
// Call the function and store the result
val newTotal = account.deposit(50.0)
println("New Balance: $$newTotal")
}
this KeywordSometimes, a class function's parameter might have the exact same name as a class property. To avoid confusion, you can use the this keyword.
this refers to the current object. this.name specifically means "the property name of this object," while just name refers to the parameter.
class User(var name: String) {
fun changeName(name: String) {
// this.name = class property
// name = function parameter
this.name = name
}
}
How do you call a function named startEngine() on an object named myCar?