Junior
What is the difference between the 'open' and 'final' modifiers in Kotlin?.
sobes.tech AI
Answer from AI
In Kotlin, all classes and methods are final by default, meaning they cannot be inherited or overridden.
open: Theopenmodifier makes a class or method available for inheritance or overriding. Without it, attempting to inherit or override will result in a compile error.final: This modifier explicitly indicates that a class or method cannot be inherited or overridden. It is used less frequently since this is the default behavior, but can be useful for explicitly stating the intention or to override an open method to make it final in the hierarchy.
// Classes are final by default
class MyFinalClass // Cannot be inherited
open class MyOpenClass { // Can be inherited
// Methods are final by default
fun finalMethod() {} // Cannot be overridden
open fun openMethod() {} // Can be overridden
}
class MyDerivedClass : MyOpenClass() {
// Override the open method
override fun openMethod() {}
// Cannot override finalMethod() from MyOpenClass
// override fun finalMethod() {} // Compile error
// Can declare a method final in a derived class
final override fun openMethod() {
// Additional logic
}
}
// A class inheriting from MyDerivedClass
class MyAnotherDerivedClass : MyDerivedClass() {
// Cannot override openMethod() because it is final in MyDerivedClass
// override fun openMethod() {} // Compile error
}