In kotlin a class is a blueprint or template for creating objects that encapsulates related data (properties) and behavior (functions or methods) into a single, modular unit. It is a core concept of object-oriented programming (OOP) that helps structure code into reusable and manageable components
In Kotlin programming, a class is a fundamental building block used to represent real-world entities in code. Classes allow developers to combine data (properties) and behavior (functions) into a single logical unit. Understanding classes is essential for mastering object-oriented programming in Kotlin.A class in Kotlin is a blueprint or template used to create objects. It defines the structure and behavior of objects by specifying properties and functions.
class Person { var name: String = "Unknown" var age: Int = 0 fun introduce() { println("My name is $name and I am $age years old.") } }
fun main() { val person1 = Person() person1.name = "Rahul" person1.age = 25 person1.introduce() }
The primary constructor is part of the class header and allows properties to be initialized directly.
class Employee(val id: Int, var name: String, var salary: Double)
fun main() { val emp = Employee(101, "Anita", 50000.0) println(emp.name) }
Secondary constructors are useful when additional initialization logic is required.
class Student { var name: String var marks: Int constructor(name: String, marks: Int) { this.name = name this.marks = marks } constructor(name: String) { this.name = name this.marks = 0 } }
class Car(var brand: String, var speed: Int) { fun accelerate() { speed += 10 } fun displayInfo() { println("Car Brand: $brand, Speed: $speed") } }
| Modifier | Description |
|---|---|
| public | Accessible everywhere (default) |
| private | Accessible only inside the class |
| protected | Accessible in subclasses |
| internal | Accessible within the same module |
A data class is used to hold data and automatically generates useful methods.
data class Product(val id: Int, val name: String, val price: Double)
class BankAccount(var accountNumber: String, var balance: Double) { fun deposit(amount: Double) { balance += amount } fun withdraw(amount: Double) { if (amount <= balance) { balance -= amount } else { println("Insufficient balance") } } }
A class in Kotlin is a blueprint that defines properties and methods used to create objects.
A class is a template, while an object is an instance created from that template.
Yes, Kotlin supports one primary constructor and multiple secondary constructors.
Use a data class when your class is mainly used to store data and needs auto-generated methods.
Kotlin encourages immutability using val, but classes can be mutable when var is used.
Copyrights © 2024 letsupdateskills All rights reserved