0
0
Kotlinprogramming~30 mins

Why classes define behavior and state in Kotlin - See It in Action

Choose your learning style9 modes available
Why classes define behavior and state
📖 Scenario: Imagine you are creating a simple program to represent a car. Each car has some details like its color and speed, and it can perform actions like accelerating or braking.
🎯 Goal: You will build a Kotlin class called Car that holds the car's color and speed (state) and has functions to change the speed (behavior). This will show how classes combine state and behavior.
📋 What You'll Learn
Create a class named Car with two properties: color (String) and speed (Int).
Add a function accelerate() that increases speed by 10.
Add a function brake() that decreases speed by 10 but not below 0.
Create an instance of Car with color "Red" and speed 0.
Call accelerate() twice and brake() once on the instance.
Print the final speed of the car.
💡 Why This Matters
🌍 Real World
Classes help programmers create objects that represent things in real life, like cars, users, or products, with their details and actions.
💼 Career
Understanding how classes combine state and behavior is fundamental for software development jobs, especially in object-oriented programming languages like Kotlin.
Progress0 / 4 steps
1
Create the Car class with properties
Create a Kotlin class called Car with two properties: color of type String and speed of type Int. Initialize speed to 0.
Kotlin
Need a hint?

Use class Car(val color: String, var speed: Int = 0) to define the class with properties.

2
Add accelerate and brake functions
Inside the Car class, add a function accelerate() that increases speed by 10, and a function brake() that decreases speed by 10 but does not allow speed to go below 0.
Kotlin
Need a hint?

Define fun accelerate() to add 10 to speed. Define fun brake() to subtract 10 but keep speed at least 0.

3
Create a Car instance and change speed
Create a variable myCar as an instance of Car with color "Red" and speed 0. Then call accelerate() twice and brake() once on myCar.
Kotlin
Need a hint?

Create myCar with Car("Red"). Call accelerate() twice and brake() once on it.

4
Print the final speed of the car
Write a println statement to display the final speed of myCar using myCar.speed.
Kotlin
Need a hint?

Use println(myCar.speed) to show the current speed.