kotlin 接口
接口 (Interface)
Kotlin interfaces can contain abstracts methods as well as concrete methods(methods with implementations).
Kotlin接口可以包含抽象方法和具体方法(带有实现方法的方法)。
Kotlin interfaces can have properties but these need to be abstract or to provide accessor implementations.
Kotlin接口可以具有属性,但是这些属性必须是抽象的或提供访问器实现。
Interfaces cannot store state, which makes them different from abstract classes.
接口无法存储状态,这使它们与抽象类不同。
Kotlin methods and properties by default abstract, if no implementation provided.
默认情况下,如果未提供实现,则Kotlin的方法和属性将抽象。
Kotlin's class can implement one or more interfaces.
Kotlin的类可以实现一个或多个接口。
程序演示Kotlin中接口的示例 (Program demonstrate the example of Interface in Kotlin)
package com.includehelp
// Declare Interface
interface Organization{
// Abstract Property
val age:Int
// Property with accessor implementations
val name:String
get() = "Trump"
// interface method with implementations
fun printAge(){
println("Age : $age")
}
// abstract method
fun getSalary(salary:Int)
}
// class implements interface
class Manager:Organization{
// override interface abstract property
override val age=32
// Override interface abstracts method
override fun getSalary(salary: Int) {
println("Your Salary : $salary")
}
}
// Main function, Entry Point of Program
fun main(){
// Create instance of class
val organization=Manager()
// Call function
organization.printAge()
// Call function
organization.getSalary(10000)
// Access properties
println("Name : ${organization.name}")
}
Output:
输出:
Age : 32
Your Salary : 10000
Name : Trump
翻译自: https://www.includehelp.com/kotlin/example-of-interface.aspx
kotlin 接口