
Class And Objects in Kotlin
📌 Classes and Objects in Kotlin
In Kotlin, a class is a blueprint for creating objects. An object is an instance of a class that contains properties (variables) and methods (functions).
✅ 1. Defining a Class in Kotlin
Classes in Kotlin are declared using the
class
keyword.It can contain properties and functions.
📌 Basic Class Example
fun () { val person1 = Person() person1.name = "John" person1.age = 25 person1.displayInfo() val person2 = Person() person2.name = "Emma" person2.age = 30 person2.displayInfo()}
Output:
Name: John, Age: 25Name: Emma, Age: 30
✅ 3. Class Constructor
Primary Constructor
Kotlin provides a concise way to declare a constructor within the class definition using the
constructor
keyword.
class Person(val name: String, var age: Int) { fun () { println("Name: $name, Age: fun () { val person = Person("Alice", 28) person.displayInfo()}
Output:
Name: Alice, Age: 28
val name
→ Immutable property.var age
→ Mutable property.
Secondary Constructor
You can define a secondary constructor using the
constructor
keyword.
class Employee { var name: String var age: Int constructor(name: String, age: Int) { this.name = name this.age = age } fun () { println("Name: $name, Age: fun () { val emp = Employee("David", 35) emp.displayInfo()}
Output:
Name: David, Age: 35
✅ 4. Class Functions and Methods
Functions inside a class are called methods.
class Calculator { fun (a: Int, b: fun (a: Int, b: fun () { val calc = Calculator() println("Addition: ${calc.add(5, Addition: 8Multiplication: 24
✅ 5. Inheritance in Kotlin
Kotlin supports inheritance using the :
symbol.
The parent class should be marked as open
to allow inheritance.
// Parent classopen class Animal(val name: String) { open fun () { println("Animal makes a sound") }}// Child classclass Dog(name: String) : Animal(name) { override fun () { println("$name says Woof!") }}fun () { val dog = Dog("Buddy") dog.sound()}
Output:
Buddy says Woof!
✅ 6. Object Keyword
In Kotlin, you can use the object
keyword to create:
Singleton Objects (A single instance of a class).
Anonymous Objects (For one-time use).
Singleton Object
object DatabaseConnection { fun () { println("Connected to the Database") }}fun () { DatabaseConnection.connect()}
Output:
Connected to the Database
Anonymous Object
interface ClickListener { fun ()}fun () { val buttonClick = object : ClickListener { override fun onClick() { println("Button clicked!") } } buttonClick.onClick()}
Output:
Button clicked!
✅ Conclusion
Classes define the structure of objects.
Objects are instances of classes.
Kotlin supports primary and secondary constructors.
Use
open
for inheritance andoverride
for method overriding.Use
object
for creating singletons or anonymous objects.