Kotlin 学习笔记(2)类和继承

来源:互联网 发布:淘宝app二手市场 编辑:程序博客网 时间:2024/06/15 01:19

以下是本人的学习笔记,入有任何不妥之处,随时欢迎拍砖指正。
谢谢 ^_^

1. 类

Kotlin 中使用关键字 class 声明类

class Invoice {}//如果没有具体的内容甚至可以这样定义class Invoice

2. 构造函数

在 Kotlin 中类可以有一个主构造函数和一个或多个次构造函数

class Person constructor(firstName: String) {}

如果主构造函数没有任何注解或者可见性修饰符,可以省略这个 constructor 关键字。

class Person(firstName: String) {}

主构造函数中不能有内容,如果需要初始化,使用init关键字

class Person(firstName: String) {     init {         println("Customer initialized with value ${firstName}")     }}

我们通过以下方式创建 Person

val p = Person("12")// 输出结果I/System.out: Customer initialized with value 12

3. 次构造函数

也可以用constructor作为前缀来生成次构造函数。

class Parent {   constructor(parent: Child) {       println("Customer initialized with parent")   }}
class Child(firstName: String) {  init {       println("Customer initialized with value ${firstName}")   }}

通过以下方式创建

val name = Parent(Child("Xiao Ming"))// 输出结果I/System.out: Customer initialized with value Xiao MingI/System.out: Customer initialized with parent

类如果没有任何参数,那么默认是 public 的,如果需要私有就在上边加『private』 修饰符

class Person private constructor ()

当构造函数被『private』所修饰时,无法创建对象

编译会报错,提示 Person 已被私有化。

下面是构造函数上有默认的值提供,构造器会提供一个空参函数来初始化,并使用默认值。

class Person (val PersonName: String = "")

我们通过以下方式创建 Person

val p = Person()

4. 继承

Kotlin 中所有类都有一个共同的超类 Any

class Parent // 从 Any 隐式继承

open关键字修饰的类允许其他类从这个类继承

open class Parent(p: Int)class Child(p: Int) : Parent(p)

4.1 覆盖方法

当子类被open修饰时,才可以被继承,默认情况(即没有 open) 下是 final 修饰的无法继承。
当被open 修饰的类中有被open修饰的方法时,可以被子类重写,用 override 来修饰。如下例中的 paly( )

open class Parent(p: Int) {    open fun play() {}    fun doHomeWork() {}}class Child(p: Int) : Parent(p) {    override fun play() {        super.play()    }}

如果想让 play 只被重写一次那么,需要加final
也就是说当类中的方法被 final 修饰时,子类无法继承

class Child(p: Int) : Parent(p) {    final override fun play() {        super.play()    }}

当类没有被 open所修饰(也就是默认 final 修饰),那么类中的方法也不能用open 修饰

4.2 覆盖属性

属性也可以被覆盖,可以用一个 var 属性覆盖一个 val 属性,但反之则不行。

interface Foo {    val count: Int}class Bar1(override val count: Int) : Fooclass Bar2 : Foo {    override var count: Int = 0}

4.3 覆盖规则

kotlin 中,接口可选的去实现里面的方法。

open class A {    open fun f() { print("A") }    fun a() { print("a") }}interface B {    fun f() { print("B") } // 接口成员默认就是“open”的    fun b() { print("b") }}class C() : A(), B {    // 编译器要求覆盖 f():    override fun f() {        super<A>.f() // 调用 A.f()        super<B>.f() // 调用 B.f()  }}

上面例子中类 C 继承了类 A 和接口 B ,类 C 可以调用 a()b(),而f()存在歧义,C 不知道他该继承谁的方法,所以我们需要对相同名称的方法进行重写覆盖,这样我们就可以通过自定义方法的形式来消除歧义。

关于我

一只成长中的图图。

感谢

参考自:
https://www.kotlincn.net/docs/tutorials/android-plugin.html

https://huanglizhuo.gitbooks.io/kotlin-in-chinese/content/GettingStarted/Basic-Syntax.html

原创粉丝点击