Skip to main content
Kotlin Basics
CHAPTER 13 Beginner

Classes and Objects

Updated: May 18, 2026
5 min read

# CHAPTER 13

Classes and Objects

1. Chapter Introduction

Up to this point, we have used standard data types like Int and String. But what if you are building an HR application? You need a User type or an Employee type. This is where Object-Oriented Programming (OOP) begins. In this chapter, we will learn how to create blueprints (Classes) and bring them to life as actual entities in memory (Objects).

2. Learning Objectives

By the end of this chapter, you will be able to:
  • Define a class in Kotlin.
  • Instantiate an Object from a class.
  • Add Properties (state) to a class.
  • Add Methods (behavior) to a class.
  • Understand visibility modifiers (public, private).

3. What is a Class?

A Class is a blueprint or template. It defines what data an entity holds, and what actions it can perform. For example, a Car blueprint says every car has a color and can drive().
kotlin
1234567891011
// Creating the Blueprint
class Car {
    // Properties (State)
    var color: String = "Red"
    var brand: String = "Toyota"

    // Methods (Behavior)
    fun drive() {
        println("The $color $brand is driving!")
    }
}

4. What is an Object?

An Object is an actual, physical instance of that blueprint created in the computer's memory. You can create multiple objects from a single class.

In Java, you create objects using the new keyword (e.g., Car myCar = new Car()). Kotlin completely removed the new keyword! You just call the class name like a function.

kotlin
12345678910111213
fun main() {
    // Creating two Objects (Instances) of the Car class
    val myCar = Car()
    val yourCar = Car()

    // Modifying properties of a specific object
    yourCar.color = "Blue"
    yourCar.brand = "Ford"

    // Calling methods
    myCar.drive()   // Outputs: The Red Toyota is driving!
    yourCar.drive() // Outputs: The Blue Ford is driving!
}

5. Properties vs. Java Fields

In Java, you have to write hidden private fields and expose them using bulky Getter and Setter methods (getColor(), setColor()). In Kotlin, you simply declare properties. Kotlin automatically generates the Getters and Setters for you under the hood!
kotlin
123456789
class User {
    var name: String = "Guest" // Kotlin generates getName() and setName() silently
}

fun main() {
    val user = User()
    user.name = "Alice" // Calls the invisible Setter!
    println(user.name)  // Calls the invisible Getter!
}

6. Visibility Modifiers

Sometimes you want to hide data inside a class so other parts of the code cannot accidentally break it. This is called Encapsulation.
  • public: (Default in Kotlin). Accessible from anywhere.
  • private: Accessible ONLY from inside the class itself.
  • protected: Accessible inside the class and its subclasses (covered in Chapter 15).
  • internal: Accessible only within the same module (e.g., the same App or Library).
kotlin
123456789101112131415161718
class BankAccount {
    // Hidden from the outside world!
    private var balance: Double = 0.0

    // Public method to safely interact with the hidden data
    fun deposit(amount: Double) {
        if (amount > 0) {
            balance += amount
            println("Deposited $amount")
        }
    }
}

fun main() {
    val account = BankAccount()
    // account.balance = 1000000.0 // ERROR! Cannot access 'balance': it is private
    account.deposit(50.0) // Safe interaction
}

7. Mini Project: Employee Management System

Let's build a simple system to model an Employee.
kotlin
1234567891011121314151617181920212223242526
class Employee {
    var name: String = ""
    var position: String = ""
    private var salary: Double = 0.0

    fun setSalary(amount: Double) {
        if (amount >= 30000) {
            salary = amount
        } else {
            println("Salary too low for company standards.")
        }
    }

    fun printDetails() {
        println("Employee: $name, Role: $position")
    }
}

fun main() {
    val emp = Employee()
    emp.name = "John Doe"
    emp.position = "Software Engineer"
    
    emp.setSalary(85000.0)
    emp.printDetails()
}

8. Common Mistakes

  • Using the new keyword: Java developers constantly type val c = new Car(). The Kotlin compiler will throw a syntax error. Just use Car().
  • Forgetting parentheses: Typing val myCar = Car instead of val myCar = Car(). The first assigns the class reference, the second actually creates the object instance in memory.

9. Best Practices

  • Hide State: Make properties private if they should not be modified directly from outside the class. Force users to use methods (like deposit()) to interact with sensitive data safely.

10. Exercises

  1. 1. Create a class Book with properties title and author.
  1. 2. Add a method readBook() that prints "Reading [title] by [author]".
  1. 3. In main(), create an object, set the properties, and call the method.

11. MCQs with Answers

Question 1

What is a Class in OOP?

Question 2

What is an Object in OOP?

Question 3

What keyword is required to instantiate an object in Kotlin?

Question 4

What does Kotlin automatically generate when you declare a property like var name = "Bob"?

Question 5

What is the default visibility modifier for classes and properties in Kotlin?

Question 6

If you mark a property as private, who can access it?

Question 7

What OOP principle refers to hiding internal data and requiring users to interact with it via public methods?

Question 8

How do you call a method drive() on an object named myCar?

Question 9

Which modifier allows access only within the same module (e.g., the same compiled project)?

Q10. Can you create multiple objects from a single Class? a) Yes b) No Answer: a) Yes.

12. Interview Questions

  • Q: Explain why Kotlin eliminated the new keyword. (Answer: To make the language more concise and readable. Calling a constructor looks exactly like calling a regular function).
  • Q: How does Kotlin handle Getters and Setters differently from Java?

13. Summary

Classes and Objects form the core of modern software architecture. A class defines the structure (properties) and the capabilities (methods). Kotlin massively improves upon Java's OOP syntax by removing the new keyword and automatically generating Getters and Setters, eliminating hundreds of lines of boilerplate code while maintaining strict Encapsulation via visibility modifiers.

14. Next Chapter Recommendation

Our Car class hardcoded the color to "Red". If we want a blue car, we have to change it *after* creating it. This is inefficient. In Chapter 14: Constructors and Initialization, we will learn how to pass data into an object at the exact moment it is created.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·