1. Overview
In this article, we will understand the differences between Class, Type, and object in Kotlin
2. Kotlin Class and Object
Let’s first understand the Kotlin class and object. Most of the programmers might have already came across these concepts.
Class and Object are basic concepts of Object-Oriented Programming (OOPS).
A class is a user-defined blueprint or template from which we create objects. It contains a set of properties and methods, meaning behavior or state that the object of its type can support. We can create a single or multiple objects from class which shares the common behavior specified by its class.
An object is an instance of a class and an actual entity that exists in real.
Here is an simple example.
interface Animal { fun makeSound() fun eat() } class Giraffe implements Animal { override fun makeSound() { println("Giraffee makes sound") } override fun eat() { println("Giraffe eats leaves") } } class Dog implements Animal { override fun makeSound() { println("Dog barks") } override fun eat() { println("Dog eats food") } } fun main() { val dogObj = Dog() val giraffeObj = Giraffe() }
In the above example, Dog is the class and dogObj
is the object or instance of Dog class. We can create multiple objects for the class Dog
and all of those will exhibit the same behaviors eat
and makeSound
.
Now, as we have seen about Class and Object, let’s discuss about Class and Type
3. Kotlin Class and Type
Class and Type are often used interchangeably but those are not identical.
Types provide interface information that determines to which operations an object can respond. It is of a more inclusive category. An interface, a primitive, an array, a class are all types.
Classes provide implementation information including initial values for instance variables and the method body.
Let’s take the above example. The type of dogObj
is Dog
. Here, Dog
is the class name and also a type.
Both Dog
and Giraffe
implements the interface Animal
. So you can say Dog
and Giraffe
are of type Animal
. Additionally, both Dog
and Giraffe
creates their own type.
Dog
class is of type of Dog
(its own) and also Animal
. Giraffe
class is of type of Giraffe
and also Animal
. Here, dogObj
has many types Dog
and Animal
whereas girafeeObj
has types Giraffe
and Animal
. Both dogObj
and girafeeObj
has the same type Animal.
So an object can have many types, and objects of different classes can have the same type.
4. Generic class and its types
A generic class have multiple types. Let’s take the below expression. The A
is a class and it can accept various types like A<Int>
, A<String>
, A<List<String>>
and so on
class A<T>
5. Conclusion
In this article, you learned the class, object, type and also generic class along with its type.
If you like to learn about other Kotlin topics, we encourage you to refer our Kotlin articles.