0
0
Kotlinprogramming~5 mins

Class declaration syntax in Kotlin

Choose your learning style9 modes available
Introduction

A class is like a blueprint to create objects that hold data and actions together. Declaring a class lets you organize your code and model real-world things.

When you want to group related data and functions about something, like a Car or a Person.
When you need to create multiple similar objects with their own data.
When you want to reuse code by creating objects from the same blueprint.
When you want to model real-world things in your program clearly.
When you want to keep your code organized and easy to understand.
Syntax
Kotlin
class ClassName {
    // properties and functions
}

The class name should start with a capital letter by convention.

Inside the curly braces, you can add properties (data) and functions (actions).

Examples
A simple class named Person with two properties: name and age.
Kotlin
class Person {
    var name: String = ""
    var age: Int = 0
}
A class with a primary constructor that sets brand and year when creating a Car object.
Kotlin
class Car(val brand: String, val year: Int)
A class Dog with a function bark that prints a sound.
Kotlin
class Dog {
    fun bark() {
        println("Woof!")
    }
}
Sample Program

This program defines a Book class with title and author. It has a function to print a description. In main, it creates a Book and calls describe.

Kotlin
class Book(val title: String, val author: String) {
    fun describe() {
        println("'$title' by $author")
    }
}

fun main() {
    val myBook = Book("1984", "George Orwell")
    myBook.describe()
}
OutputSuccess
Important Notes

Classes can have constructors to set initial values easily.

Properties inside classes can be mutable (var) or read-only (val).

Functions inside classes define what objects can do.

Summary

Classes are blueprints to create objects with data and actions.

Use class ClassName { } to declare a class in Kotlin.

Inside classes, add properties and functions to model real things.