Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can not inherit from final class

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'".enter image description here

enter image description here

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: enter image description here

This is my first time creatin a library. Can someone show me how can I manage to fix this problem?

like image 370
CyberUser Avatar asked Aug 12 '17 08:08

CyberUser


People also ask

Can you inherit from final class?

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.

Which class in Java Cannot be inherited?

What cannot be inherited ? Constructors. Although, the subclass constructor has to call the superclass constructor if its defined (More on that later!) Multiple classes.

Can a final class be overridden?

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.

Why super classes Cannot be final classes?

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.


2 Answers

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

like image 117
Bob Avatar answered Sep 25 '22 14:09

Bob


Use the open annotation, read the documentation here. https://kotlinlang.org/docs/reference/classes.html

like image 34
Imran Avatar answered Sep 22 '22 14:09

Imran