Abstract classes

The abstract keyword in Kotlin defines a class or a member whose implementation is missing or incomplete. Abstract classes can be extended but cannot be instantiated. Abstract classes do not have to have abstract members, but an abstract member has to be defined inside an abstract class. Let's define an abstract class that has two abstract members, a property and a function:

abstract class BaseUser {
abstract val name: String
abstract fun login()

fun logout(){
println("Logging out")
}
}

You can see that we also have one non-abstract function. Abstract classes can have state and non-abstract members. You can also see that an abstract function doesn't have an implementation, it only has a signature. The same for the abstract property, it doesn't return any value. If you had the abstract modifier on a member that has an implementation, you'd get a compiler error. This BaseUser class wouldn't compile:

abstract class BaseUser {

//compiler error
abstract val name: String = ""

//compiler error
abstract fun login() {
//login the user
}

fun logout(){
println("Logging out")
}
}

Now, let's create a class that inherits from our abstract class. All the members that are marked with the abstract keyword have to be implemented, that is, overridden by the class that extends the abstract class:

class User(override val name: String) : BaseUser() {

override fun login(){
println("Logging out")
}
}
..................Content has been hidden....................

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