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:
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
nameproperty is private, so it cannot be accessed directly from outside the class. Instead, it is accessed and modified using public methods (setNameandgetName).
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:
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
Dogclass inherits from theAnimalclass and overrides themakeSoundmethod.
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):
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:
Drawing a circle Drawing a square
Example (Method Overloading):
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):
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):
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.
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.
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.
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:
| Concept | Description | Example |
|---|---|---|
| Encapsulation | Bundling data and methods, restricting access using access modifiers. | Private properties with getters/setters. |
| Inheritance | A class inherits properties and methods from another class. | class Dog : Animal() |
| Polymorphism | Objects of different classes can be treated as objects of a common superclass. | Method overriding and overloading. |
| Abstraction | Hiding 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
Post a Comment