用abstract关键字声明的类称为abstract class。抽象类无法实例化。就是说,无涯教程不能创建抽象类的对象。除非将抽象类的方法和属性明确声明为抽象,否则它们是非抽象的。
abstract class A { var x = 0 abstract fun doSomething() }
抽象类是部分定义的类,方法和属性,它们没有实现,但必须实现为派生类。如果派生类未实现基类的属性,则它也应成为抽象类。
抽象类或抽象函数不需要使用open关键字注释,因为它们默认情况下是打开的。抽象成员函数不包含其主体。如果成员函数包含在抽象类的主体中,则不能将其声明为抽象。
在此示例中,有一个抽象类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<String>){ val obj = Honda() obj.run(); }
输出:
Honda is running safely..
非抽象的开放成员函数可以在抽象类中重写。
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") //要更改创建函数的主体,请使用 File | Settings | File Templates println("Honda City is running..") } } fun main(args: Array<String>){ val car = Car() car.run() val city = City() city.run() }
输出:
Car is running.. Honda City is running..
在上面的示例中,本田抽象类扩展了Car类及其函数run()。本田类重写Car类的run()函数。本田类未提供run()函数的实现,因为它也被声明为抽象。本田类的抽象函数run()的实现由City类提供。
在此示例中,包含抽象函数simpleInterest()的抽象类Bank接受三个参数p,r和t。 SBI和PNB类提供了simpleInterest()函数的实现并返回结果。
链接:https://www.learnfk.comhttps://www.learnfk.com/kotlin/kotlin-abstract-class.html
来源:LearnFk无涯教程网
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<String>) { 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") }
输出:
SBI interest is 150.0 PNB interest is 135.0
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)
PPT设计进阶 · 从基础操作到高级创意 -〔李金宝(Bobbie)〕