Abstract classes

An abstract class is a generic concept and it does not belong to a concrete idea. We do not create an instance of an abstract class; its only responsibility is to facilitate the creation of other classes. An abstract class is used to define which behaviors a class should have instead of how it should be implemented. Take a look at the following example from the previous section:

open class Person (val fName: String, var lName: String, var pAge: Int) {

fun speak() {
println("My name is $fName $lName age is $pAge")
}
fun greet() {
println("Hi there...$fName ")
}
}

class Student(fName: String, lName: String, pAge: Int , val studentId : String) : Person(fName,lName,pAge) {
...
...
}

Notice that the Person class is a normal class and we can create an instance of it:

val person = Person("Bob","Peter",25)

In this case, however, we do not need to create an instance of the Person class, because person is an abstract idea. We want to prevent objects from being created from the Person class. This is what the abstract class is used for. Update the Person class, replace the open keyword with abstract, and the rest of the implementation will remain the same:

abstract class Person (val fName: String, var lName: String, var pAge: Int) {
}

The program will execute without any errors unless we create an instance of the Person class in the main function. In this case, the Kotlin compiler will throw the following error:

Cannot create an instance of an abstract class

The abstract class can have both normal and abstract functions. We will look at abstract functions in the following section.

While creating an abstract class, it is not necessary to provide the open keyword because the abstract class is open by default.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.189.186