Kotlin Class and Objects

In this tutorial you will learn about the Kotlin Class and Objects and its application with practical example.

Kotlin Class and Objects

Kotlin Langauge supports both procedural programming and object-oriented programming. It supports procedural programming with the use of functions.

Table Of Contents

In object-oriented programming langauge we can divide a complex problems into smaller sets with the help of objects. Object has two characteristics: state and behavior.
Let’s take a real world example, Dogs have state(name,color,breed,hungry) and behavior(barking,fetching,wagging tail).

How to use Function:

Kotlin Class: Class is a group of object which have common properties. It is a blueprint of objects. It’s a logical entity .

Define a Class in Kotlin:

Example: Let’s get understand it by an example.

So here is the Name of Class User, The Property of class is isActive is a type of boolean(can be true or false), It have two member function that are Active() and inActive().

Visibility Modifiers: Kotlin provides a number of Visibility Modifiers that can be used in classes, objects, properties, member function etc. In Above example I have used private visibility modifiers for isActive Property , it means it can use only within the class.

There are four visibility modifiers that are:

1.private: This modifiers can access or visible only inside the class.

2.public: This modifiers can access or visible everywhere.

3.protected: This modifiers can access or visible to the class and its subclass.

4.internal: It is accessble inside the module.

 

How to use Object in Kotlin: The specification for the Object is defined when a class is defined, We need to create Objects for accessing members which are defined within the class. See How we can use it.

Here U1 and U2 are the two Objects of User class.

 

How to Access Member : Now let’s see how can we access the member functions, check below syntax.

U1.Active()

Second Way to access it.

U2.isActive = true

 

Complete Example : Now let’s see complete example of use of class, objects and modifiers in Kotlin. Check below code.

Output:The output of above code will print the user status using “printUserStatus” function. Will look like below image.

class-obj-1

In this tutorial we have learn about the Kotlin Class and Objects and its application with practical example. I hope you will like this tutorial.