As I'm working in the middle of some kotlin project I got a confusion like whether a child class implements another parent class or else implementing an interface? like I am using some interfaces and classes from a jar which I am not aware a lot about it could someone explain to me a way to solve this since I am new to kotlin.
For Example:
a class definition
abstract class Employee (val firstName: String, val lastName: String) {
abstract fun earnings(): Double
}
which is extended by some other class
abstract class Employee (val firstName: String, val lastName: String) {
// ...
fun fullName(): String {
return lastName + " " + firstName;
}
}
Similarly an Interface
class Result
class Student
interface StudentRepository {
fun getById(id: Long): Student
fun getResultsById(id: Long): List<Result>
}
Interface implementation
class StudentLocalDataSource : StudentRepository {
override fun getResults(id: Long): List<Result> {
// do implementation
}
override fun getById(id: Long): Student {
// do implementation
}
}
In Kotlin, to inherit from a class you have to write its primary constructor, so you will always see the parent class followed by (), sometimes with things inside.
Interfaces don't need this. You just write the names of the interfaces and that's it.
So if you see brackets after a name, that's a parent class. Otherwise its an interface.
Consider the following example:
abstract class Employee(val firstName: String, val lastName: String) {
abstract fun earnings(): Double
}
interface Hireable {
fun hire()
}
class HireableEmployee(firstName: String, lastName: String) : Employee(firstName, lastName), Hireable {
override fun earnings(): Double {
return 10000.0
}
override fun hire() {
//...
}
}
as you can see the parent class is declared with a constructor invocation Employee(firstName, lastName), the interface declaration Hireable has no parentheses behind it.
So in Kotlin extends corresponds to the () behind the name signalling that this is a constructor invocation and therefore the parent class. implements has no special syntax, just the name.
For more Information about interfaces see https://kotlinlang.org/docs/reference/interfaces.html
About class hierarchies see https://kotlinlang.org/docs/reference/classes.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With