constructor: constructor
This, super
simply talk about inheritance, the two keywords this and super are similar to java;
this is the one that calls itself, and super is the
main activity that calls the parent class:
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
AAA("学生")
var b = BBB("小王")
}
}
open class AAA {
constructor(name: String) {
// Log.v("wz", "$name A")
System.out.println("wz = $name A")
}
constructor(name: String, age: Int) {
// Log.v("wz", "我是AAA的两个参数的构造方法")
System.out.println("wz = 我是AAA的两个参数的构造方法")
}
init {
// Log.v("wz", "222")
System.out.println("wz = 222")
}
}
class BBB : AAA {
constructor(name: String) : this(name, 0) {
// Log.v("wz", "我是BBB的一个参数的构造方法")
System.out.println("wz = 我是BBB的一个参数的构造方法")
}
constructor(name: String, age: Int) : super(name, age) {
// Log.v("wz", "我是BBB的两个参数的构造方法")
System.out.println("wz = 我是BBB的两个参数的构造方法")
}
}
//var b = BBB("小王")
The class BBB inherits AAA, where BBB has a one-parameter constructor and a two-parameter constructor respectively; the one-parameter constructor uses the this keyword to call its own two-parameter constructor; and the two-parameter constructor uses The constructor of the parent class with two parameters called by the super keyword; here is the data printed by the console:
System.out: wz = 222
System.out: wz = 学生 A
System.out: wz = 222
System.out: wz = 我是AAA的两个参数的构造方法
System.out: wz = 我是BBB的两个参数的构造方法
System.out: wz = 我是BBB的一个参数的构造方法
If you don't understand it, you can use debugging, and you can know it step by step.