-
Kotlin's Class
Similar to Java, a class in Kotlin is a user-defined template with properties and functions to create objects. A Kotlin class can have a primary constructor and none, one, or more secondary constructors. A class is defined using the class keyword. An object can be created using either val (immutable reference) or var (mutable reference). The typical structure of a Kotlin class is as follows:class KotlinClassName { // Properties or data members ... // Functions or methods ... }
-
Kotlin's OOP Features
Kotlin supports core Object-Oriented Programming (OOP) principles such as Abstraction, Polymorphism, Encapsulation, and Inheritance, using classes, objects, and interfaces. -
Abstraction
In Kotlin, an abstract class is declared using the abstract keyword. Abstract classes cannot be instantiated. They are open by default, meaning they can be subclassed. Abstract methods and fields are declared with the abstract keyword. Non-abstract members of an abstract class are final by default and cannot be overridden. -
Encapsulation
Kotlin provides several visibility modifiers to enforce encapsulation:
private: Members are accessible only within the Kotlin file where they are defined.
public: Members are accessible from anywhere. By default, Kotlin classes and members are public.
protected: Members are accessible within the class and its subclasses.
internal: Members are accessible within the same module. -
Inheritance
By default, all classes in Kotlin are final (non-inheritable). To allow inheritance, a class must be marked with the open modifier. A child class inherits the methods and properties of the parent class and can also define its own. Additionally, Kotlin allows the use of extension functions to extend the functionality of a class without using inheritance. -
Polymorphism
Polymorphism allows the same method defined in a parent class to behave differently based on the object. Kotlin supports both compile-time polymorphism (method overloading) and runtime polymorphism (method overriding). In method overloading, the method name remains the same, but the parameter list or return type differs. In method overriding, the method call is resolved at runtime by the JVM. -
Functional Programming
Kotlin combines object-oriented and functional programming paradigms. It supports lambdas (anonymous functions treated as values), higher-order functions (functions that take other functions as parameters or return them), and immutability to enable functional programming.