Classes and Objects in Kotlin

Learn via video courses
Topics Covered

Overview

In Kotlin, classes are templates for creating objects that encapsulate data and behavior. Objects in Kotlin are instances of classes, representing tangible entities. Classes define properties or attributes and methods or functions, supporting inheritance and hierarchies. Kotlin also offers concise data class syntax for data-heavy objects, generating useful methods automatically. This system forms a crucial foundation for organized and maintainable code.

Classes

Classes in Kotlin are foundational constructs that facilitate structured and organized code creation. They serve as blueprints for generating objects, and instances of the class. Each class defines properties (attributes) and methods (functions) encapsulating data and behaviour, offering a modular way to model real-world entities and interactions.

Properties within a class represent object attributes, ranging from simple data types to custom types, with mutability options and default values. Methods define class behaviours, enabling objects to execute specific tasks. Kotlin supports single and multiple inheritance, creating class hierarchies and extending functionality from parent to subclass. The open keyword allows inheritability, while final restricts further inheritance, promoting controlled and modular design.

The syntax for defining a class in Kotlin is as follows:

Let us now see an example of classes in kotlin based on the above syntax:

In this section, you would have learned in detail how to define classes in Kotlin to use them in the program.

Objects

Objects in Kotlin are instances of classes that represent tangible entities or instances within a program. Objects are created from class blueprints and encapsulate both data and behaviour defined within the class. They enable you to work with concrete instances and interact with their properties and methods.

In Kotlin, an object is a fundamental language construct used to define a singleton instance of a class. A singleton is a design pattern that ensures only one instance of a particular class exists throughout the application's lifecycle. Objects in Kotlin are designed to provide a simple and concise way to achieve this pattern.

Key characteristics of objects in Kotlin include:

  1. Singleton Nature: An object in kotlin represents a single instance of its associated class. This ensures that no matter how many times the object is accessed or referenced, it always points to the same instance. Example:
  1. Lazy Initialization: Lazy initialization is a memory optimization technique where objects are instantiated only when they are first accessed. This strategy delays the creation of instances until their use is required, conserving memory resources. Once an object has been accessed for the first time and subsequently accessed again, the previously created instance is reused, preventing redundant object creation and maintaining efficient memory utilization.
  2. Properties and Functions: Just like regular classes, objects in kotlin can contain properties (variables) and functions (methods). These properties and functions are accessed using the object's name, similar to accessing static members in other programming languages.

Examples:

This demonstrates how properties and functions can be encapsulated within an object in kotlin and accessed using the object's name. 4. Companion Objects: Objects in kotlin can also be defined within classes as companion objects. These objects are associated with the class and can hold static members that are shared across instances of the class. This allows for organizing related functionalities in a cohesive manner.

  1. Inheritance and Subclassing: Unlike regular classes, objects in kotlin cannot be inherited or subclassed. This is because objects are inherently designed to represent a single instance, and extending them would break the singleton principle.
  1. Usage Scenarios: Objects in kotlin are particularly useful in scenarios where you need a single, globally accessible instance of a class. Common use cases include managing configuration settings, handling database connections, or implementing caching mechanisms.

Objects in kotlin are defined using the object keyword, followed by a name and a code block. This code block contains the properties, functions, and behaviors that define the object's functionality.

We shall learn more about objects in kotlin and how do we create and use them in our kotlin program in the upcoming sections.

Creating an object

Let us now create an object in kotlin for the class made above:

In this case, person is an instance of the Person class, with the properties name and age set to "Alice" and 25, respectively.

Accessing the properties of the class

For the class described above, we shall now learn how to access the class properties. The class properties can be accessed as demonstrated in the code below:

In the code above, we've accessed the name and age properties of the person1 object using dot notation (object.property). Additionally, we've called the introduce() method on both person1 and person2 objects to display their information.

Accessing the member functions of the class

Let us look at the class definition below:

In the provided code:

  • myCar.accelerate(20) invokes the accelerate() method of the myCar object, increasing its speed by 20 km/h and displaying the updated speed.
  • myCar.accelerate(30) invokes the accelerate() method again, this time increasing the speed by 30 km/h and displaying the updated speed.
  • myCar.brake(15) invokes the brake() method, decreasing the car's speed by 15 km/h and displaying the updated speed.

By calling these member functions on the myCar object, you're performing actions that are defined within the class. This encapsulation of behavior allows you to control the car's behavior and characteristics in a structured and modular manner.

Conclusion

  1. In Kotlin, classes provide blueprints for creating objects that encapsulate data and behavior. Objects are instances of classes, representing tangible entities.
  2. Kotlin's robust support for classes and objects enables the creation of diverse and structured entities.
  3. Classes in Kotlin offer a structured way to create organized code. Properties define attributes, ranging from basic data types to more complex structures. Methods define behaviors that objects can perform.
  4. Objects are instances of classes, representing concrete entities. You can create objects by calling the class constructor.
  5. Member functions within classes encapsulate behavior. You can access these functions using object.method() syntax.