Kotlin(4)面向对象

类与对象

一般类

抽象类

嵌套类

是一种静态内部类

内部类

修饰符

属性

构造器

继承

父类val,子类var是可以的,反之不行

接口

函数重写

实现多个接口是,可能会遇到同一方法继承多个实现的问题

interface A {

fun foo() { print("A") } // 已实现

fun bar() // 未实现,没有方法体,是抽象的

}

interface B {

fun foo() { print("B") } // 已实现

fun bar() { print("bar") } // 已实现

}

class C : A {

override fun bar() { print("bar") } // 重写

}

class D : A, B {

override fun foo() {

super<A>.foo()

super<B>.foo()

}

override fun bar() {

super<B>.bar()

}

}

fun main(args: Array<String>) {

val d = D()

d.foo()

d.bar()

}

枚举类

扩展

扩展函数不具备运行时的多态

//父类

open class Shape2

//子类

class Rectangle2:Shape2()

//针对Shape2定义的扩展函数

fun Shape2.getName()="Shape2"

//针对Rectangle2定义的扩展函数

fun Rectangle2.getName() = "Rectangle2"

fun printClassName(s:Shape2){ //静态解析

println(s.getName())

}

fun main(){

printClassName(Rectangle2())

}

打印出来是Shape2

数据类与封装类

密封类是一种特殊的抽象类,不能实例化

相关推荐
QING61810 小时前
Kotlin inline 实战详解 —— 新手须知
android·kotlin·android jetpack
Ehtan_Zheng10 小时前
Kotlin Flow:combine()、merge() 和 zip() 的区别 —— 不要再互相替代使用
kotlin
高林雨露11 小时前
Java 转 Kotlin 对照开发指南
java·开发语言·kotlin
o丁二黄o11 小时前
语义版本控制:用Gemini镜像站实现合同条款的深度差异分析与风险追踪
javascript·kotlin·scala
Kapaseker12 小时前
为什么 Java 的数组需要 new 出来
android·java·kotlin
赏金术士1 天前
第七章:状态管理实战与架构总结
android·ui·kotlin·compose
Kapaseker2 天前
搞懂变换!精通 Compose 绘制(二)
android·kotlin
赏金术士2 天前
Compose 教学项目
android·kotlin·compose
赏金术士2 天前
Jetpack Compose 状态提升(State Hoisting)完全指南
android·kotlin·compose
Hali_Botebie2 天前
岭回归(Ridge Regression),也称为L2正则化回归
数据挖掘·回归·kotlin