1. In kotlin, the default classes are closed. If you want to open inheritance for a certain class, you must use the open keyword to modify it
Methods in the class are also turned off by default. If the subclass needs to rewrite the parent class method, it must also be modified with open.
1) Define the parent class and use open to inherit the class. Use open to open the rewrite of the function.
//The parent class must be modified with open to be inheritedopen class Person(val name:String) { var age = 0 //The function defined by the parent class must be modified with open, and the subclass can be rewrited open fun doWork(){ println("do nothing") } }
2) Define subclasses. The properties do not need to be modified by the open field. Subclasses inherit the properties of the parent class by default
class Student(name: String) : Person(name) { override fun doWork() { println("do homework") } } fun main() { val student = Student("HanMei") = 20 println() println() () }
Check the type of an object through the is keyword.
val student = Student("HanMei") println(student is Student) println(student is Person) println(student is Any)
In Java, instanceof is used to check the type of an object.
Student student = new Student(); (student instanceof Student); (student instanceof Person);
3. There is a superclass Any in kotlin. All classes are subclasses of it. Just like the Object superclass in Java.
The same method as Object is also defined in the Any class. But in Any, they are all empty implementations. The real implementation is done by the kotlin compiler.
public open class Any { public open operator fun equals(other: Any?): Boolean public open fun hashCode(): Int public open fun toString(): String }
In a defined subclass, these methods can be rewrited
class Student(name: String) : Person(name) { override fun doWork() { println("do homework") } override fun toString(): String { return "name:$name age:$age" } override fun hashCode(): Int { return () } override fun equals(other: Any?): Boolean { return (other) } }
is a type conversion operator. You can convert subclass types into parent class and abstract class interface.
Define a method that receives the parent class type.
fun sayHello(p: Person) { println("Hello," + ) }
Due to the polymorphism of the class, we can directly assign the subclass type to the parent class type.
It can also be converted to parent class type through the as field, which we usually don't do.
val student = Student("HanMei") sayHello(student) sayHello((student as Person))
This is the end of this article about the detailed introduction to the inheritance implementation of Kotlin class. For more related inheritance content of Kotlin class, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!