In my last tutorial, we understood basic introduction about Kotlin and basic features to get a quick start building an Android application. In this series, we will learn about of Classes and Objects in Kotlin. Sounds good 🙂
But before if you have not checked my last tutorial then I would be recommended checking my all post for better understanding which is based on basic of Kotlin to get started in Android part series. Here is the link of Basic of Kotlin to get started in Android part-1 and Basic of Kotlin to get started in Android part-2.
Classes and Objects
Classes and Objects in kotlin are almost similar to Java. It contains the access modifiers and constructor. But one thing in Kotlin is that Fields has no more with Kotlin. Kotlin classes are all about the properties. And properties are initialized before the constructor.
If we are talking about Constructor then Kotlin has updated constructor schema. Now in Kotlin Constructor will be two different types. One is Primary Constructor and other is Secondary Constructor.
The class can declare secondary constructors, which are prefixed with the constructor. but it is not required for a primary constructor. We are very much familiar with the access modifiers in Java but in Kotlin it is the little bit modified. Ok, Let’s check what are the visibility modifiers available in Kotlin.
Kotlin has four visibilities:
1. private
2. protected
3. internal
4. public
If we do not declare any visibility modifier, the public is used by default, which means that your declarations will be visible everywhere.
If we declared access modifier as a private, then it will only be visible in the class. If we declare access modifier as internal then it is visible everywhere in the same module.
Protected is not available for top-level declarations. It can access in the same class and their subclasses.
Let’s see the example that how we can use classes in kotlin?
class TestClass(private var context: Context) { init { getAppName() } private fun getAppName() { val appName = context.getString(R.string.app_name) print("App Name is: $appName") } }
Here init is the initializer block to initialized anything which is required for a class. Let’s see how can we write the primary and secondary constructor in kotlin.
// primary constructor class Person1(name: String) { init { println("My name is : $name") } } // primary constructor class Person2(var name: String) { // secondary constructor constructor(name: String, parent: Person2) : this(name) { print("constructor is: $name") } init { println("init block called") } }
Generic Class: Generic class could be any type of Object. Let’s see how can we create generic type class and objects.
// generic type class Box<T>(t: T) { var value = t } // T will be any type of Object ex String , Int or Object var obj = Box(1); var obj2 = Box("Name") var obj3 = Box(Maruti("Maruti-800", "Blue"))
Nested Class: A class which is inside the class is called nested class. We know very much clear in Java. The things are similar to Kotlin also. Let’s see how can we create the nested class and their object in Kotlin?
// nested class class A { private val nameTitle: String = "Kotlin" fun getName(): String { return nameTitle; } class B { fun getObjectName(): String { var objName = "New Kotlin" return objName; } } } // create the object and get the data var objValue1 = A().getName(); // it will give "Kotlin" var objValue = A.B().getObjectName() // it will get "New Kotlin'
Inner Class: Inner class will be prefixed with an inner keyword.
// Inner class class C { private val nameTitle: String = "Kotlin" fun getName(): String { return nameTitle; } inner class D { fun getObjectName(): String { var objName = "New Kotlin" return objName; } } } var objInnerValue1 = C().getName() // Kotlin var objInnerValue2 = C().D().getObjectName() // new Kotlin
Anonymous Inner Class: A class which does not have any name is called anonymous class. Let’s see how can we write an anonymous class in Kotlin?
class NumberEvent { } abstract class Numbers { abstract fun addNumbered(e: NumberEvent) abstract fun substractNumber(e: NumberEvent) } class E { fun addNumberListener(number: Numbers) { } } fun anonymousClass() { E().addNumberListener(object : Numbers() { override fun addNumbered(e: NumberEvent) { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } override fun substractNumber(e: NumberEvent) { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } }) }
Abstract, Data class and Inheritance:
If I explain what are those in Kotlin before we need to understand the same thing in Java. I guess everyone knows about the abstract class and data class (POJO) and inheritance. I want to remind all those in simple java example.
public abstract class Car { private String name; Car(String name){ this.name = name; } } public class Maruti extends Car{ private String model; private String color; Maruti(String model, String color){ super("Maruti"); this.model = model; this.color = color; } }
How can we create the object of an abstract class? It can’t because Car class is an abstract class and we can not create an object of abstract class but when we want to use this class we need to inherit from other class and instantiate this class.
Maruti focus = new Maruti("maruti 800", "blue")
If I create the same thing in Kotlin then It is pretty simple and easy. Let’s see.
abstract class Car(val name: String) {} class Maruti(val model: String, val color: String) : Car("Maruti") // -> here Maruti is inherited from Car, So Maruti can access the all property of car. val maruti = Maruti("Maruti-800", "Blue") // if we want to create a new Object of Maruti with property name and value val maruti2 = Maruti(model = "Maruti-800", color = "Green")
Maruti class is inherited from Car class, So Maruti can access all property of Car. The car has one open method, So whenever Maruti class inherit Car class then need to override this method or function. Let’s see with an example what am I talking about?
abstract class Car(val name: String){ fun getName() { } open fun getCarName(): String{ return name; } } class Maruti(val model: String, val color: String) : Car("Maruti"){ override fun getCarName(): String { return super.getCarName() } } // creating object val maruti = Maruti("Maruti-800", "Blue")
Wrapping up: we understood that Kotlin is an awesome language which is taken a good part of Java. Let’s make this language more powerful to build an awesome android app by using Kotlin. You can check the official website to get more details.
Ok, In my next tutorial, we will learn more features of Kotlin.
So please do subscribe your email to get the newsletter on this blog and if you feel this post is good then do not forget to share and comment below. Happy Coding 🙂
I am a very enthusiastic Android developer to build solid Android apps. I have a keen interest in developing for Android and have published apps to the Google Play Store. I always open to learning new technologies. For any help drop us a line anytime at contact@mobologicplus.com
Hi everyone, In this article, we are going to learn how to hide the production… Read More
Hello everyone, Today in this article, we are going to learn about localisation to support… Read More
Hello everyone, In this article, we are going to learn something to handle the callback… Read More
In this article, we are learning about the run time permissions for request permission launchers.… Read More
Hello everyone. In my last tutorial, we learned about the Jetpack Compose introduction and about applying the… Read More
Hello everyone, In this article, we are going to learn about the Jetpack Compose with… Read More