Java – cannot inherit from final class

I just created my first Android library In another application, I want to extend a class from it But it shows an error: "can't extend to the final 'library. Com. Kukaintro. Activities. Kukaintro'"@ L_ 419_ 1@

As you can see, no superclass is final If I click on the superclass kukaintro (in the application rather than the Library), it will say:

This is the first time I have set up a library Can someone tell me how to solve this problem?

Solution

In kotlin, unlike Java, by default, all classes are implicitly marked final If you want to inherit from a class, you must explicitly add the open keyword before the class declaration

open class Base(p: Int) {

}

If you want to override any function in the superclass, you must add the open keyword to those functions in the superclass again, and the override keyword is required for overriding functions in subclasses

Examples from 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

The following is a discussion of this language design: https://discuss.kotlinlang.org/t/classes-final-by-default/166

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>