Kotlin – open, final, abstract
In KOTLIN, all the classes are defaultfinal
. If you need to allow it to be inherited, then you need to useopen
Statement:
// This class has a `Open` attribute and can be inherited by other categories
open class People: Speakable{
// `` Open` is implemented and covered, this method is also `Open`
override fun say() {}
// `Final` Method, must not be written
The method of
fun sayHello() {}
// `Open` can be inherited and covered
open fun sayName() {}
}
Of course, you can also stop some methods from being written:
open class People: Speakable{
// `Final` to modify a method that originally has the` Open` attribute, so that it can not be written again
final override fun say() {}
}
In Kotlin,
The usage ofabstract
is almost consistent with Java, and I will no longer be embarrassed. It is worth mentioning that when you use itabstract
When the modifier is modified, you can ignoreopen
modifiers, because it isabstract
modified class defaults to beopen
Properties.
modifiers | Corresponding class members | Note |
---|---|---|
final |
cannot be written | All methods and classes in Kotlin arefinal attribute |
open |
can be written | Need to be clearly pointed out |
abstract |
Must be written | cannot be instantiated, the default hasopen Properties. |
override |
How to write a superclass | If it is not specified asfinal , then defaultopen attribute |
The above form is only applicable to the base class. For the interface class, you basically don’t use itfianl
、open
、abstract
, because the interface class is defaultopen
, and cannot be declared asfinal
, if the method of the interface class does not have a function body, then it isabstract
, but you don’t need to point out that he isabstract
.