-
Kotlin Classes
A class in Kotlin is a blueprint for creating objects. It can contain properties (data) and functions (behavior). Classes are defined with theclasskeyword and support a primary constructor in the class header plus optional secondary constructors.class Person(val name: String, var age: Int) { // properties and functions go here } -
Core OOP Principles in Kotlin
Kotlin fully supports the four fundamental object-oriented principles: -
Abstraction
Hiding implementation details and exposing only essential features. Achieved withabstractclasses and interfaces.abstract class Shape { abstract fun draw() = println("Drawing...") abstract fun area(): Double } -
Encapsulation
Bundling data and methods while controlling access through visibility modifiers:public— visible everywhere (default)private— visible only in the same fileprotected— visible in the class and its subclassesinternal— visible within the same module
-
Inheritance
Kotlin classes arefinalby default. Use theopenkeyword to allow inheritance:open class Animal class Dog : Animal()A class can inherit from only one parent class (single inheritance). -
Polymorphism
Same interface, different behavior:- Compile-time polymorphism — method overloading
- Runtime polymorphism — method overriding with the
overridekeyword
open class Animal { open fun sound() = "..." } class Cat : Animal() { override fun sound() = "Meow" }