繁体   English   中英

如何区分kotlin的类继承(在java中扩展)和接口实现(实现)这里kotlin使用(:)两者?

[英]How to Differentiate between kotlin's class inheritence(extends in java) and interface implementation(implements in ) here kotlin uses ( : ) for both?

当我在某个kotlin项目中工作时,我得到了一个混乱,比如子类是否实现了另一个父类或者实现了一个接口? 就像我正在使用罐子里的一些接口和类而我不太了解它可能会有人向我解释一个解决这个问题的方法,因为我是kotlin的新手。
例如:
一个类定义

abstract class Employee (val firstName: String, val lastName: String) {
    abstract fun earnings(): Double
}

这是由其他一些类扩展

abstract class Employee (val firstName: String, val lastName: String) {
    // ... 

    fun fullName(): String {
        return lastName + " " + firstName;
    }
}

同样是一个接口

class Result
class Student 

interface StudentRepository {
    fun getById(id: Long): Student
    fun getResultsById(id: Long): List<Result>
}

接口实现

class StudentLocalDataSource : StudentRepository {
    override fun getResults(id: Long): List<Result> {
       // do implementation
    }

    override fun getById(id: Long): Student {
        // do implementation
    }
}

在Kotlin中,要继承一个类,你必须编写它的主要构造函数,所以你总是会看到父类跟着() ,有时候里面有东西。

接口不需要这个。 你只需要写出接口的名称就可以了。

因此,如果您在名称后面看到括号,那就是父类。 否则它是一个接口。

请考虑以下示例:

abstract class Employee(val firstName: String, val lastName: String) {
    abstract fun earnings(): Double
}

interface Hireable {
    fun hire()
}

class HireableEmployee(firstName: String, lastName: String) : Employee(firstName, lastName), Hireable {
    override fun earnings(): Double {
        return 10000.0
    }

    override fun hire() {
        //...
    }
}

正如您所看到的,父类是使用构造函数调用Employee(firstName, lastName)声明的,接口声明Hireable后面没有括号。

所以在Kotlin中, extends对应于名称后面的() ,表示这是一个构造函数调用,因此是父类。 implements没有特殊的语法,只有名称。

有关接口的更多信息,请参阅https://kotlinlang.org/docs/reference/interfaces.html

关于类层次结构,请参阅https://kotlinlang.org/docs/reference/classes.html

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM