Kotlin 简明教程
Kotlin - Abstract Classes
Kotlin抽象类类似于Java抽象类,无法被实例化。这意味着我们不能创建抽象类的对象。但是,我们可以从Kotlin抽象类继承子类。
A Kotlin abstract class is similar to Java abstract class which can not be instantiated. This means we cannot create objects of an abstract class. However, we can inherit subclasses from a Kotlin abstract class.
使用 abstract 关键字在类名前方声明Kotlin抽象类。抽象类的属性和方法均为 non-abstract ,除非我们显式使用 abstract 关键字使其变为抽象。如果我们要在子类中覆盖这些成员,只需在子类中在其前方使用 override 关键字即可。
A Kotlin abstract class is declared using the abstract keyword in front of class name. The properties and methods of an abstract class are non-abstract unless we explictly use abstract keyword to make them abstract. If we want to override these members in the child class then we just need to use override keyword infront of them in the child class.
abstract class Person {
var age: Int = 40
abstract fun setAge() // Abstract Method
fun getAge() { // Non-Abstract Method
return age
}
}
Example
以下是显示Kotlin抽象类及其通过子类实现的简单示例:
Following is a simple example showing a Kotlin Abstract class and its implementation through a child class:
abstract class Person(_name: String) {
var name: String
abstract var age: Int
// Initializer Block
init {
this.name = _name
}
abstract fun setPersonAge(_age:Int)
abstract fun getPersonAge():Int
fun getPersonName(){
println("Name = $name")
}
}
class Employee(_name: String): Person(_name) {
override var age: Int = 0
override fun setPersonAge(_age: Int) {
age = _age
}
override fun getPersonAge():Int {
return age
}
}
fun main(args: Array<String>) {
val employee = Employee("Zara")
var age : Int
employee.setPersonAge(20)
age = employee.getPersonAge()
employee.getPersonName()
println("Age = $age")
}
当你运行上述 Kotlin 程序时,它将生成以下输出:
When you run the above Kotlin program, it will generate the following output:
Name = Zara
Age = 20
此处,类 Employee 源自抽象类 Person 。我们在子类 Employee 中实现了了一个抽象属性和两个抽象方法。这里值得注意的是,所有抽象成员都已在子类中使用 override 进行了覆盖,如果子类继承抽象类,则这是强制性的。
Here, a class Employee has been derived from an abstract class Person. We have implemented one abstract property and two abstract methods in the child class Employee. Here notable point is that all the abstract members have been overriden in the child class with the help of override, which is a mandatory for a child class if it inherits an abstract class.
总结一下,在其声明中包含 abstract 关键字的Kotlin类称为抽象类。
To summarise, A Kotlin class which contains the abstract keyword in its declaration is known as abstract class.
-
Abstract classes may or may not contain abstract methods, i.e., methods without body ( public void get(); )
-
But, if a class has at least one abstract method, then the class must be declared abstract.
-
If a class is declared abstract, it cannot be instantiated.
-
To use an abstract class, you have to inherit it from another class, provide implementations to the abstract methods in it.
-
If you inherit an abstract class, you have to provide implementations to all the abstract methods in it.