Subscribe Now

* You will receive the latest news and updates on your favorite celebrities!

Trending News

Blog Post

Android Kotlin Tutorial: How to create a Class and Object ?
Kotlin

Android Kotlin Tutorial: How to create a Class and Object ?

Today we are going to learn How to Create a Class and Object in Kotlin. Kotlin is an Object Oriented Programming language like Java. Object Oriented  Programming language allows us to solve complex problems using Objects. In this, tutorial we will learn what is class and object in Kotlin?

 

Kotlin Class

“A class is a blueprint for the object and the object is its state. “

For Example, we can just think of a class as a sketch(prototype) of a car. It contains all the details about the tyres, engines, windows, etc. Based on these descriptions we build the car. Car is the object.

Since many cars can be made from the same descriptions, we can create many objects from a class.

How to define a class in Kotlin?

To define a class in Kotlin, class keyword is used.

class ClassName{

//property

//member functions

}

Example:

class CarModel {

    //Property
    private var carColor: String = ""

    //member function
    fun setCarColor(color: String) {
        carColor = color
    }

    fun getCarColor(): String {
        return carColor
    }

}

Here, we defined a class named CarModel.

The class has one property carColor and two member functions setCarColor and getCarColor. 

Kotlin Objects

Whereas a class describes structures that can be instantiated as and when desired and allows for as. many instances as needed. An object is a static single instance of a Class.

Let’s create objects of CarModel class. To access members declare within the class, you need to create objects.

Example:

var audiCar = CarModel()
var bmwCar = CarModel()

In the above example, we have created two objects audiCar and bmwCar.

How to access members of a Kotlin Class?

You can access properties and member functions of a class by using ” . ” notation. For Example

audiCar.setCarColor("BLACK")
audiCar.getCarColor()

In the above example, we have access serCarColor function and getCarColor function using object with ” . ” notation. Now, remember this you cannot access the value of audioCar object using bmwCar .

For Example,
If we set car color as “BLACK” using audioCar object. we will not get car color as “BLACK” using bmwCar.

If you don’t know about the variable declaration is Kotlin. Please check this blog. Contact me on twitter or put comments below if you want me to create blog on specific topic.

Watch full video of this blog on

 

 

Visit my Github Repositories for Coding Samples:
https://github.com/lokeshdesai403?tab=repositories

Related posts

Leave a Reply

Required fields are marked *