Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lære Using Properties and Methods Together | Constructors and Methods
Kotlin Classes and Objects

bookUsing Properties and Methods Together

Stryg for at vise menuen

State vs. Behavior

When you define a class in Kotlin, you are describing both the state and the behavior of its objects. The state of an object is represented by its properties—these are variables that hold data about the object. The behavior of an object is defined by its methods—these are functions that perform actions, often using or modifying the object's properties.

Properties keep track of information, such as a bank account's balance or a user's name. Methods let you perform actions like depositing money or updating a user's profile. By combining properties and methods, you create classes that model real-world objects more accurately.

Practical Example

To see how properties and methods work together, look at the following example of a simple bank account class.

BankAccount.kt

BankAccount.kt

copy

In the code above, the BankAccount class has a balance property that stores the current amount of money in the account. The deposit and withdraw methods allow you to change the balance by adding or subtracting money. Notice how the methods use the balance property to both check and update the state of the object.

To use the BankAccount class, you create an object and call its methods. For example, creating an account with an initial balance of 100.0, then depositing 50.0, increases the balance to 150.0. Withdrawing 30.0 reduces it to 120.0. If you try to withdraw more than the available balance, the method prevents it and prints a warning. This demonstrates how properties and methods work together to define what an object is and what it can do.

question mark

Which of the following best describes the difference between a property and a method?

Vælg det korrekte svar

Var alt klart?

Hvordan kan vi forbedre det?

Tak for dine kommentarer!

Sektion 2. Kapitel 4

Spørg AI

expand

Spørg AI

ChatGPT

Spørg om hvad som helst eller prøv et af de foreslåede spørgsmål for at starte vores chat

Sektion 2. Kapitel 4
some-alt