Kotlin教程:抽象类声明与示例

使用abstract关键字声明的类称为抽象类。 无法实例化抽象类。 意思是,不能创建抽象类的对象。 显式使用abstract关键声明类,才能表示抽象类的方法和属性,否则它是非抽象的。

抽象类声明

abstract class A {
var x = 0
abstract fun doSomething()
}

抽象类是部分定义的类,方法和属性,它们不是实现,但必须在派生类中实现。 如果派生类没有实现基类的属性或方法,那么它也是一个抽象类。

抽象类或抽象函数不需要使用open关键字进行批注,因为它们默认是开放的。 抽象成员函数不包含实现主体。 如果成员函数在抽象类中包含有函数的实现,则不能将声明为abstract

具有抽象方法的抽象类的示例

在这个例子中,有一个抽象类Car包含一个抽象函数run()run()函数的实现由它的子类Honda提供。

abstract class Car{
abstract fun run()
}
class Honda: Car(){
override fun run(){
println("Honda is running safely..")
}
}
fun main(args: Array){
val obj = Honda()
obj.run();
}

执行上面示例代码,得到以下结果 -

Honda is running safely..

Shell

非抽象的open成员函数可以在抽象类中重载。

open class Car {
open fun run() {
println("Car is running..")
}
}
abstract class Honda : Car() {
override abstract fun run()
}
class City: Honda(){
override fun run() {
// TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
println("Honda City is running..")
}
}
fun main(args: Array){
val car = Car()
car.run()
val city = City()
city.run()
}

Kotlin

执行上面示例代码,得到以下结果 -

Car is running..
Honda City is running..

Shell

在上面的例子中,一个抽象类Honda扩展了Car类和它的run()函数。 Honda类覆盖Car类的run()函数。 Honda类没有给出run()函数的实现,因为将它也声明为abstractHonda类的抽象函数run()的实现由City类提供。

抽象类示例

在此示例中,包含抽象函数simpleInterest()的抽象类:Bank,它接受三个参数prtSBI类和PNB类提供simpleInterest()函数的实现并返回结果。

abstract class Bank {
abstract fun simpleInterest(p: Int, r: Double, t: Int) :Double
}
class SBI : Bank() {
override fun simpleInterest(p: Int, r: Double, t: Int): Double{
return (p*r*t)/100
}
}
class PNB : Bank() {
override fun simpleInterest(p: Int, r: Double, t: Int): Double{
return (p*r*t)/100
}
}
fun main(args: Array) {
var sbi: Bank = SBI()
val sbiint = sbi.simpleInterest(1000,5.0,3)
println("SBI interest is $sbiint")
var pnb: Bank = PNB()
val pnbint = pnb.simpleInterest(1000,4.5,3)
println("PNB interest is $pnbint")
}

Kotlin

执行上面示例代码,得到以下结果 -

SBI interest is 150.0
PNB interest is 135.0

//原文出自【易百教程】,商业转载请联系作者获得授权,非商业转载请保留原文链接:https://www.yiibai.com/kotlin/kotlin-abstract-class.html#article-start