1. Introduction
In Kotlin, public is a visibility modifier, and the open keyword is related to inheritance, which means they serve different purposes. In this tutorial, we’ll see the difference between open and public keywords in detail.
2. Kotlin’s public Keyword
As we know, all classes, functions, and properties can have their visibility modifiers. There are four visibility modifiers in Kotlin: private, protected, internal, and public.
Unlike Java, public is the default visibility modifier in Kotlin, which means all declarations are visible everywhere out of the box. And when we need to “hide” some class, function, or property, we’ll have to explicitly specify the appropriate modifier: private, protected, or internal.
Taking that into account, using the public keyword explicitly isn’t necessary. Some IDEs like IntelliJ IDEA highlight it, saying that it’s redundant.
Local variables, functions, and classes can’t have visibility modifiers.
3. Kotlin’s open Keyword
As we already mentioned, the open keyword is related to inheritance. When compared with Java, it would be the opposite of the final keyword in Java, which prevents classes from being inherited and methods from being overridden.
3.1. Using the open Keyword With Classes
Kotlin classes, by default, are final and can’t be inherited or extended.
Let’s try to inherit a class that’s not declared as open:
class SomeClass {}
class SomeChildClass : SomeClass() {}
We’ll see that the IDE shows the corresponding error:
This type is final, so it cannot be inherited from
This is where open comes into play. All we have to do is add open to the declaration of the class we want to inherit from:
open class SomeClass {}
class SomeChildClass : SomeClass() {}
3.2. Using the open Keyword With Properties and Functions
Similarly to classes, properties and functions are also final by default in Kotlin. So, if we need to override any of them, we have to make them open in the parent class. Otherwise, the compiler will complain.
4. Conclusion
In this article, we’ve looked through the differences between using open and public keywords in Kotlin.
We’ve learned that they have different purposes. The open keyword allows classes, functions, and properties to be extended, while public is a visibility modifier that doesn’t have any explicit usage since all classes, functions, and properties are publicly visible by default.