- 方法默认实现:
- 接口:Kotlin中接口可以有默认实现的方法。默认实现的方法使用
fun
关键字定义,并给出具体实现。多个类实现同一个接口时,若未重写接口的默认实现方法,将使用接口的默认实现。例如:
interface MyInterface {
fun myMethod() {
println("This is a default implementation in interface")
}
}
- 抽象类:抽象类中的方法可以是抽象的(只有声明,没有实现,使用
abstract
关键字修饰),也可以有具体实现的方法。但抽象类中抽象方法必须在子类中实现。例如:
abstract class MyAbstractClass {
abstract fun abstractMethod()
fun concreteMethod() {
println("This is a concrete method in abstract class")
}
}
- 成员属性定义:
- 接口:接口中可以定义属性,但只能是抽象属性(没有初始化器),且不能有
private
修饰符。接口属性的访问器可以有默认实现。例如:
interface MyInterface {
val myProperty: String
get() = "Default value"
}
- 抽象类:抽象类中可以定义普通属性(有初始化器),也可以定义抽象属性。抽象属性同样需要在子类中实现。抽象类的属性可以有不同的访问修饰符,如
private
、protected
等。例如:
abstract class MyAbstractClass {
protected val myConcreteProperty = "Concrete property in abstract class"
abstract val myAbstractProperty: String
}
- 实现多继承方式:
- 接口:一个类可以实现多个接口,从而实现类似多继承的功能,不同接口的功能相互叠加。例如:
interface Interface1 {
fun method1()
}
interface Interface2 {
fun method2()
}
class MyClass : Interface1, Interface2 {
override fun method1() {
println("Implementing method1 from Interface1")
}
override fun method2() {
println("Implementing method2 from Interface2")
}
}
- 抽象类:Kotlin中一个类只能继承一个抽象类,所以不能像接口那样通过实现多个抽象类来实现类似多继承的效果。例如:
abstract class Abstract1 {
abstract fun method1()
}
abstract class Abstract2 {
abstract fun method2()
}
// 下面代码会报错,因为Kotlin不支持多重继承抽象类
// class MyClass : Abstract1, Abstract2 {
// override fun method1() {
// println("Implementing method1 from Abstract1")
// }
// override fun method2() {
// println("Implementing method2 from Abstract2")
// }
// }
- 实例化:
- 接口:接口不能被实例化,它只是定义了一组方法和属性的契约。
- 抽象类:抽象类同样不能被实例化,但它可以作为其他类的基类,为子类提供通用的实现和属性。