Kotlin Class and Objects

Latest posts
Get notified of the Latest Sport News Update from Our Blog
Share

In Kotlin, classes and objects are used to represent objects in the real world.

Class: A class is like a blueprint or a template for creating objects. It defines the properties (attributes) and behaviors (methods) that objects created from this class will have. class keyword is used to define a class.

Syntax of the class declaration: 

class ClassName {
    // Properties (attributes)
    // Methods (functions)
    // Initializer blocks (optional)
    // Nested classes, objects, interfaces (optional)
}

The class can contain various elements. Here is a list of elements that can be included in a class:

Creation of class

class Person {
    var name: String = ""
    var age: Int = 0
    
    fun speak() {
        println("Hello, my name is $name")
    }
}

In this example, we’ve defined a Person class with two properties (name and age) and one method (speak()).

Object:

It represents the real-world entities, which have states and behavior. It is an instance of a class.

Let’s consider an example where we defined model a Person as a real-world entity with states (such as name and age) and behavior (such as speak() method).

You can create multiple objects from the same class, each with its own set of values for the properties.

How to create object of class?

Object (an instance) of a class can be created using the class name followed by parentheses. Here’s a basic example:

val person1 = Person()
fun main() {

    //Creating an object of the Person class
 
    val person1 = Person()
    person1.name = "Alice"
    person1.age = 30
    
    val person2 = Person()
    person2.name = "Bob"
    person2.age = 25
    // Accessing the state (properties) of the object
    
    person1.speak() // Output: Hello, my name is Alice
    person2.speak() // Output: Hello, my name is Bob
}

In this example, we’ve created two objects (person1 and person2) from the Person class. Each object has its own set of name and age properties. If change the age of person1 than value will not be changed of age for person2

Related blogs

Nullam quis risus eget urna mollis ornare vel eu leo. Aenean lacinia bibendum nulla sed 

Subscribe to get 15% discount