Inheritance and overloading methods of Kotlin classes
inherit
All classes in Kotlin have a common superclass: Any
, which is the default superclass for classes with no supertype.
class Example // Implicitly inherits from Any
Any
No java.lang.Object
; in particular , it has no member functions other than equals()
, hashCode()
and . toString()
See the Java Interoperability section for more details.
To declare an explicit supertype, put the type after the colon in the class header:
open class Base(p: Int)
class Derived(p: Int) : Base(p)
If the class has a primary constructor, the base type can (and must) be initialized with the primary constructor's arguments.
If the class has no primary constructor, each secondary constructor must super
initialize the base type with the keyword, or delegate to another constructor. Note that in this case, different auxiliary constructors can call different constructors of the base type:
class MyView : View {
constructor(ctx: Context) : super(ctx)
constructor(ctx: Context, attrs: AttributeSet) : super(ctx, attrs)
}
An open( open
) annotation on a class is the opposite of what Java ends up doing: it allows others to inherit the class. By default, all classes in Kotlin are final
, it corresponds to valid Java usage , the documentation for design and inheritance or disallow it.
overloaded method
As mentioned earlier, unlike Java, Kotlin requires explicit annotation (call it open
) and overrides for overridable members:
open class Base {
open fun v() {}
fun nv() {}
}
class Derived() : Base() {
override fun v() {}
}
Derived.v()
Override ( override
) annotation is required. If the ( ) comment is missing override
, the compiler will throw an error. open
If there is no annotation on a function , as in Base.nv()
, it is illegal to declare a method with the same signature in a subclass, with or without the override( override
) annotation or not. In final
a class (such as a class that does not use open
annotations) then overriding members is prohibited.
A member marked as override( override
) is itself open, i.e. it can be overridden in subclasses. If you want to suppress re-overwriting, use the final
keyword:
open class AnotherDerived() : Base() {
final override fun v() {}
}
father class:
open class father { var chactor:String="extrovert" open fun action(){ println("Love to speak loudly!!!") } }
son type:
class son:father() { //The way the subclass inherits the parent class override fun action(){ //method overloading println("Son is very good, talk less!!!!!!!") } }
test file:
fun main(args: Array<String>) { var sons=son() // object declaration println("The son's character ${sons.chactor}") //The son inherits the variable of the parent class sons.action() }
operation result:
The son's personality is extroverted The son is very good, talk less! ! ! ! ! ! ! !