OOPS Concepts in Kotlin

 Kotlin is a modern, statically-typed programming language that fully supports Object-Oriented Programming (OOP) concepts. Below is an explanation of the four main OOP concepts in Kotlin, along with examples.

1. Encapsulation

Encapsulation is the practice of bundling data (properties) and methods (functions) that operate on the data into a single unit, called a class. It also involves restricting direct access to some of an object's components, which is achieved using access modifiers.

Example:

kotlin
Copy
class Person {
    private var name: String = ""

    fun setName(newName: String) {
        name = newName
    }

    fun getName(): String {
        return name
    }
}

fun main() {
    val person = Person()
    person.setName("John Doe")
    println("Name: ${person.getName()}") // Output: Name: John Doe
}
  • Explanation: The name property is private, so it cannot be accessed directly from outside the class. Instead, it is accessed and modified using public methods (setName and getName).


2. Inheritance

Inheritance allows a class (called a subclass or derived class) to inherit properties and methods from another class (called a superclass or base class). In Kotlin, all classes are final by default, meaning they cannot be inherited unless explicitly marked as open.

Example:

kotlin
Copy
open class Animal(val name: String) {
    open fun makeSound() {
        println("$name makes a sound")
    }
}

class Dog(name: String) : Animal(name) {
    override fun makeSound() {
        println("$name barks")
    }
}

fun main() {
    val dog = Dog("Buddy")
    dog.makeSound() // Output: Buddy barks
}
  • Explanation: The Dog class inherits from the Animal class and overrides the makeSound method.


3. Polymorphism

Polymorphism allows objects of different classes to be treated as objects of a common superclass. It can be achieved through method overriding (runtime polymorphism) or method overloading (compile-time polymorphism).

Example (Method Overriding):

kotlin
Copy
open class Shape {
    open fun draw() {
        println("Drawing a shape")
    }
}

class Circle : Shape() {
    override fun draw() {
        println("Drawing a circle")
    }
}

class Square : Shape() {
    override fun draw() {
        println("Drawing a square")
    }
}

fun main() {
    val shapes: List<Shape> = listOf(Circle(), Square())
    for (shape in shapes) {
        shape.draw() // Calls the overridden method
    }
}
  • Output:

    Copy
    Drawing a circle
    Drawing a square

Example (Method Overloading):

kotlin
Copy
class Calculator {
    fun add(a: Int, b: Int): Int {
        return a + b
    }

    fun add(a: Double, b: Double): Double {
        return a + b
    }
}

fun main() {
    val calc = Calculator()
    println(calc.add(2, 3)) // Output: 5
    println(calc.add(2.5, 3.5)) // Output: 6.0
}

4. Abstraction

Abstraction is the process of hiding the implementation details and showing only the necessary features of an object. In Kotlin, abstraction is achieved using abstract classes and interfaces.

Example (Abstract Class):

kotlin
Copy
abstract class Vehicle {
    abstract fun start()
    abstract fun stop()
}

class Car : Vehicle() {
    override fun start() {
        println("Car started")
    }

    override fun stop() {
        println("Car stopped")
    }
}

fun main() {
    val car = Car()
    car.start() // Output: Car started
    car.stop() // Output: Car stopped
}

Example (Interface):

kotlin
Copy
interface Drivable {
    fun drive()
}

class Car : Drivable {
    override fun drive() {
        println("Car is being driven")
    }
}

fun main() {
    val car = Car()
    car.drive() // Output: Car is being driven
}

5. Additional OOP Features in Kotlin

Kotlin introduces some additional features that enhance OOP:

a) Data Classes

Data classes are used to hold data and automatically generate toString()equals()hashCode(), and copy() methods.

kotlin
Copy
data class User(val name: String, val age: Int)

fun main() {
    val user = User("Alice", 25)
    println(user) // Output: User(name=Alice, age=25)
}

b) Sealed Classes

Sealed classes are used to represent restricted class hierarchies, where a value can have one of the types from a limited set.

kotlin
Copy
sealed class Result
class Success(val data: String) : Result()
class Error(val message: String) : Result()

fun handleResult(result: Result) {
    when (result) {
        is Success -> println("Success: ${result.data}")
        is Error -> println("Error: ${result.message}")
    }
}

fun main() {
    val result: Result = Success("Data loaded")
    handleResult(result) // Output: Success: Data loaded
}

c) Companion Objects

Companion objects are used to define static members (properties and methods) in a class.

kotlin
Copy
class MathUtils {
    companion object {
        fun square(number: Int): Int {
            return number * number
        }
    }
}

fun main() {
    println(MathUtils.square(5)) // Output: 25
}

Summary of OOP Concepts in Kotlin:

ConceptDescriptionExample
EncapsulationBundling data and methods, restricting access using access modifiers.Private properties with getters/setters.
InheritanceA class inherits properties and methods from another class.class Dog : Animal()
PolymorphismObjects of different classes can be treated as objects of a common superclass.Method overriding and overloading.
AbstractionHiding implementation details and showing only necessary features.Abstract classes and interfaces.

Kotlin's support for OOP makes it a powerful language for building modular, reusable, and maintainable code.


Comments

Popular posts from this blog

Kotlin Math Operations and Functions Overview

Kotlin Strings: Features and Operations Guide

Kotlin Android Program (QCR) Application Codes That Read Text in Photos