I have just created my first android library. At another application I want to extend a class from the it. But it shows me an error: "Cannot extend from final 'library.com.kukaintro.activities.KukaIntro'".
As you can see none of the super classes are final. If I click at the super class KukaIntro (at the app not at the library) it says this:
This is my first time creatin a library. Can someone show me how can I manage to fix this problem?
The main purpose of using a class being declared as final is to prevent the class from being subclassed. If a class is marked as final then no class can inherit any feature from the final class. You cannot extend a final class. If you try it gives you a compile time error.
What cannot be inherited ? Constructors. Although, the subclass constructor has to call the superclass constructor if its defined (More on that later!) Multiple classes.
No, the Methods that are declared as final cannot be Overridden or hidden. For this very reason, a method must be declared as final only when we're sure that it is complete.
A final class cannot extended to create a subclass. All methods in a final class are implicitly final . Class String is an example of a final class.
In Kotlin, unlike Java, all the classes are implicitly marked final
by default. If you want to inherit from a class, you have to explicitly add open
keyword before the class declaration.
open class Base(p: Int) {
}
If you want to override any functions from the super class, again you have to add the open
keyword to those functions in the super class, and the override
keyword is mandatory for the overridden function in the sub class.
Example from the doc:
open class Foo {
open fun f() { println("Foo.f()") }
open val x: Int get() = 1
}
class Bar : Foo() {
override fun f() {
super.f()
println("Bar.f()")
}
override val x: Int get() = super.x + 1
}
Kotlin docs: https://kotlinlang.org/docs/reference/classes.html#inheritance
Here is the discussion about this language design: https://discuss.kotlinlang.org/t/classes-final-by-default/166
Use the open annotation, read the documentation here. https://kotlinlang.org/docs/reference/classes.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With