Kotlin中的类 默认都是 封闭的 , 无法被继承 , 如果要想类被继承 , 需要在定义类时 使用 open 关键字 ; 定义一个普通的 Kotlin 类 : 代码语言:javascript 代码运行次数:0 运行 classPerson(val name:String,val age:Int){funinfo(){println("name : $name, age : $age")}funsayHello(){println("Hell...
因此,要在子类中 override 它,我们需要在父类中将变量设置为open: open class MindOrks { //use open keyword to allow child class to override it open val courseId: Int = 0 //use open keyword to allow child class to override it open fun courseName(){ println("Course Name") } } class An...
openclassFather{open funaction(){println("Father")}}//constructor() 可以省略classSonconstructor():Father(){override funaction(){println("Son")}}//与上面的 Son 是等价的 , 省略了 constructor()classSon:Father(){override funaction(){println("Son")}} 4 . 子类没有主构造函数 :此时子类的每个...
openclassD{}classD1:D(){}openclassC{open fun D.foo(){println("D.foo in C")}open fun D1.foo(){println("D1.foo in C")}funcaller(d:D){d.foo()// 调用扩展函数}}classC1:C(){overridefun D.foo(){println("D.foo in C1")}overridefun D1.foo(){println("D1.foo in C1")}...
[Kotlin] Open Classes and Inheritance openclassPerson (openval name: String = "",openvar age: Int) { init {}openfun greeting(pn: String) { println("$name says hello to $pn") } }classStudent(overrideval name: String,overridevar age: Int = 18, val studentID: Long): Person(name, ...
一、使用 open 关键字开启类的继承 Kotlin 中的类 默认都是 封闭的 , 无法被继承 , 如果要想类被继承 , 需要在定义类时 使用 open 关键字 ; 定义一个普通的 Kotlin 类 : AI检测代码解析 class Person(val name: String, val age: Int) {
funmain(){varstu=Student("zhang san",23,1001)}openclassPeople(varname:String){init{println("People init, name=$name")// 1}constructor(name:String,age:Int):this(name){println("People constructor, name=$name, age=$age")// 2}}classStudent(name:String,varage:Int):People(name,age){init...
Kotlin中类默认都是封闭的,要让某个类开放继承,必须使用open关键字修饰它。 open class Product(val name: String) {fun description() = "Product: $name"open fun load() = "Nothing..."}/*** 继承* 类默认都是封闭的,要让某个类开放继承,必须使用open关键字修饰它。*/class LuxuryProduct : Product...
open classView { constructor(ctx: String):this(ctx, "attr?") { // 这里的this调用的是下面的构造方法 println("constructor(ctx: String):${ctx}") } constructor(ctx: String, attr: String) { println("constructor(ctx: String, attr: String): ${ctx}, ${attr}") ...
display() } open class Animal(name: String) { open fun display() { println("Display in Animal") } } // 继承 Animal 类的子类 class Dog(name: String) : Animal(name) { override fun display() { println("Display in Dog") } } 也可以在子类中调用父类方法 class Dog(name: String) ...