Introduction
This article will help you understand about different types of classes and their working in Kotlin.
ClassA class is a collection of data members and member methods. It behaves like a blueprint to create real-world entities, like objects.
General syntaxes to create a class without constructor and with constructor are shown below.
- class < className > (paramerers) {
-
-
- }
Object
Object is a real world entity with the ability to access members of its class. General syntax to create an object is,
- Var <objectName>= <className>()
Example
Simple program to illustrate a class and an object.
- class Book{
- var bookname:String="Handson kotlin"
- fun show() {
- println("Book name="+bookname)
- }
- }
- fun main(args:Array<String>){
- var ob=Book();
- ob.show()
- }
Nested class
Class having a class within it is known as Nested class.
- class Outerclass{
- var a:Int=5
- class Nestedclass {
- var b:Int=10
- fun show() {
-
- println("inside class value of b=" +b)
- }
- }
- }
- fun main(args:Array<String>){
- var ob=Outerclass.Nestedclass()
- ob.show()
-
- }
-
-
Explanation
In the above example, I have created a nested class ‘Nestedclass’ which has a data member ‘b’ and a member method show(). Now, the object of the nested class can access the members of the nested class only.
Inner class
An inner class is a nested class which has ‘inner’ keyword and object of the inner class is able to access the inner class members as well as outer class members.
- class Outerclass{
- var a:Int=5
- inner class Innerclass {
-
- fun show() {
-
- println("inside inner class value of a=" +a)
- }
- }
- }
- fun main(args:Array<String>){
- var ob=Outerclass().Innerclass();
- ob.show()
- }
-
-
Anonymous class
It provides the facility to create an instance of Interface and Abstract classes indirectly. An instance created with the help of anonymous class is used only once.
- interface Animal{
- fun show()
- }
- fun main(args:Array<String>){
- var cow=object :Animal{
- override fun show() {
- println("Cow is a pet animal")
- }
-
- }
- cow.show()
- }
-
-
In this example, the compiler automatically creates a nested class to implement the Animal interface which will be instantiated and the reference will be passed to cow. Now, the cow object is able to call member method show().
This cow object will be used only once, then its space will be flushed.
Data Class
Data Classes or model classes are those classes which have data members and setter and getter methods. Since the basic concept of encapsulation states that the data member of a class should be private and member methods of the class may be public, when this class is initiated, the object will access the public member methods of the class and these public methods will access private data member of the class.
To create data classes like above, Kotlin uses a keyword ‘data’.
General Syntax
- data class < ClassName > (parameters) {
-
- }
Example
Write a program to illustrate the use of data classes in Kotlin.
- data class EmployeeInfo(var empid:Int,var empname:String){
- }
- fun main(args:Array<String>){
- var object1=EmployeeInfo(101,"Mani Gautam")
- println("empid="+object1.empid+",name="+object1.empname)
- }
Explanation
The above EmployeeInfo class is a data class which has two variables ‘empid’ and ‘empname’. Because of using data keyword, Kotlin automatically creates getter and setter methods along with copy(), equals(), and hashCode() etc. You can see all these codes in IntelliJ IDE by using ctrl+shift+A ->show Kotlin bytecode -> decompile.
- public final class EmployeeInfo {
- private int empid;
- @NotNull
- private String empname;
- public final int getEmpid() {
- return this.empid;
- }
- public final void setEmpid(int var1) {
- this.empid = var1;
- }
- @NotNull
- public final String getEmpname() {
- return this.empname;
- }
- public final void setEmpname(@NotNull String var1) {
- Intrinsics.checkParameterIsNotNull(var1, "<set-?>");
- this.empname = var1;
- }
- public EmployeeInfo(int empid, @NotNull String empname) {
- Intrinsics.checkParameterIsNotNull(empname, "empname");
- super();
- this.empid = empid;
- this.empname = empname;
- }
- public final int component1() {
- return this.empid;
- }
- @NotNull
- public final String component2() {
- return this.empname;
- }
- @NotNull
- public final EmployeeInfo copy(int empid, @NotNull String empname) {….
- return new EmployeeInfo(empid, empname);
- }
- public String toString() {
- return "EmployeeInfo(empid=" + this.empid + ", empname=" + this.empname + ")";
- }
- public int hashCode() {
- return this.empid * 31 + (this.empname != null ? this.empname.hashCode() : 0);
- }
- public boolean equals(Object var1) { ...............
- }
- }
Sealed class
Sealed class is a class which can not be initiated directly. It has private constructors by default and abstract members .These are used to represent the restricted class hierarchy.
General syntax -
- sealed class < ClassName > {
-
- }
Example
Write a program to illustrate a sealed class.
- sealed class Student(id: Int) {
- fun graduate() {
- println("student of")
- }
- class Btech: Student(5) {
- fun show_btech() {
- println("BTech")
- }
- }
- class Bca: Student(5) {
- fun show_bca() {
- println("BCA")
- }
- }
- }
- fun main(args: Array < String > ) {
- var obj = Student.Btech()
- obj.graduate()
- obj.show_btech()
- Student.Btech().show_btech()
- Student.Bca().show_bca()
- }
-
- Btech
- Btech
- Bca
Explanation
I have created this example in a single file ‘Example_sealed_class.kt’. So, I am able to inherit this class in two subclasses (‘Btech and Bca’) but this class will not be inherited in another class from another file.
Enum Classes
It is a special type which allows a variable to hold the value from predefined constants. It can not initiate.
- enum class < ClassName > {
- member1,
- member2,
- member3
- }
Example
- enum class week {
- monday, tuesday, wednessday, thursday, friday, saturday, sunday
- }
- fun main(args: Array < String > ) {
-
-
-
-
-
- for (day in week.values()) {
- print(day)
- }
- }
-
Explanation
In this example, week class has 7 days as constant values. We can access these values by using class name.value’ or when we use ‘week.values() ‘ it will return an array of week class data, which can be accessed by using Foreach loop.
Genric class
As we know, to declare a variable, the data type is required which creates a restriction to have value of the specific type, i.e., an ‘Int’ type variable can hold integer value a String type variable can hold only String value. To resolve it, we can create ‘Genric’ classes to create variable of general type.
Example
- class GenricExample < T > (param: T) {
- init {
- println("curent value=$param")
- }
- }
- fun main(args: Array < String > ) {
- var obj = GenricExample < String > ("Hello Genric")
- }
-
In this example, I am creating a class ‘GenricExample’ as Genric type where programmer can specify type of parameter while initiating class. This same class can be used to create variable of different – different type.
It provides two keywords,
- out- keyword is use to assign any Generic type to its supper type
- in – keyword is use to assign supper type to Generic type
- class GenricExample < out T > (param: T) {
- init {
- println("curent value=$param")
- }
- }
- fun main(args: Array < String > ) {
- var obj = GenricExample < Int > (10)
- println(obj)
- }
-
You can use ‘in’ keyword also in similar example
Abstract class
Abstract classes have abstract methods (a method which has abstract modifier but does not have definition) and concurrent methods (the method which does not have abstract modifier but holds definition).The abstract methods of Abstract class will be overridden in its subclass. But we can’t override concurrent methods of abstract class. Abstract class can’t be initiated.
Syntax
- abstract class < ClassName > {
- abstract fun method1()
- abstract fun method2 {}
- }
Example
- abstract class Animal {
- abstract fun show()
- fun attributes() {
- println("cow has four lags")
- }
- }
- class Cow: Animal() {
- override fun show() {
- println("Cow is a pet Animal")
- }
- }
- fun main(args: Array < String > ) {
- var cow = Cow()
- cow.show()
- cow.attributes()
- }
Explanation
In the above example, there is an abstract class named Animal which has one abstract function ‘show()’ and one concurrent function ‘attributes()’.Abstract function is being overridden in Cow subclass and subclass ‘Cow ’ is being instantiated in main function.
We can’t create object of Abstract class directly.
Conclusion
Kotlin also supports maximum framework classes of Java so you can implement your Java concepts in Kotlin too. Hope this article is helpful to understand different types of classes in Kotlin.
See my previous articles if you did not see them yet and follow me to have notifications for my upcoming articles.