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

数据类与封装类

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

相关推荐
用户45989204565165 小时前
一套 KMP 多仓库版本治理工作流:用 Version Catalog + CI 把发版流水线自动化
前端·kotlin
独隅8 小时前
KMP 全栈进化:Koog 框架打造纯 Kotlin AI Agent 实战效果
开发语言·人工智能·kotlin
pengyu1 天前
【Kotlin 协程修仙录 · 元婴境 · 中阶】 | 操作符真解:Flow 中间操作符与数据流变幻术
android·kotlin
pengyu1 天前
【Kotlin 协程修仙录 · 元婴境 · 初阶】 | 冷流初啼:Flow 的基础与响应式编程的入门
android·kotlin
Kapaseker2 天前
破坏性更新 - 解读 Jetpack Compose 1.12
android·kotlin
Android-Flutter2 天前
android LeakCanary 工作原理 详解
android·kotlin
Android-Flutter2 天前
android 自定义view 详解
android·kotlin
Android打工仔2 天前
从 finally 理解程序的控制流:它为什么不是 catch 后面的代码?
android·kotlin
YXL1111YXL2 天前
续体和状态机 —— suspend 函数的 CPS 变换
android·kotlin
alexhilton2 天前
千万别误用Android Skills
android·kotlin·android jetpack