What are the kotlin classes and objects?
What are the kotlin classes and objects?
In this article, we will cover the following:
- What are kotlin classes?
- What are objects?
- What is a nested class?
- What is an inner class?
Kotlin supports both Object-oriented as well as functional programming. Kotlin also supports all the features of the OOPs, such as encapsulation, polymorphism, and inheritance.
What are kotlin classes?
kotlin class is a blueprint of the object. It is similar to Java classes. It uses keyword class to declare the kotlin class. Kotlin class has a header, properties, member functions, and the class is enclosed with curly braces.
Syntax of the class declaration:
class class_name { #header
#properties
#member_functions
}
The properties of the kotlin are initialized or declared as abstract.
What are Kotlin objects?
It is a real-time entity that has states and behavior. The characteristics of kotlin are:
- State: represents the value of an object.
- Behavior: represents the functionality of an object.
The properties and members of the class are accessed by the kotlin object. The user can create multiple objects of the one kotlin class. The kotlin object is created in two steps, first is to create the reference, and then create an object.
Example:
var object1 = className()
Here object1 is the reference, and className() is an object.
Access the properties of the class
The member functions and properties of the class are accessed by the dot(.) operator with the object.
Example:
object1.member_funtion()
What is a nested class?
Nested class means declaring a class inside another class. A nested class is, by default static, in nature. It means class member and member functions are accessed without declaring an object. A nested class is not allowed access to the members of the outer class.
Syntax of the nested class:
class outer_class {
#paramters of the outer class
class inner_class {
#parameter of the inner class
}
}
What is an inner class?
An inner class is declared inside another class with the help of the "inner" keyword. An inner class is a class that is declared inside another class. An inner class cannot be declared inside interfaces or non-inner nested classes.
Syntax of the inner class:
class outer_class {
#parameter of the outer class
class inner inner_class {
#parameter of the inner class
}
}
*Important*
The user can access the class member and member functions of the outer class even, they are private. It is the biggest advantage of using the inner class over the nested class.