Preface: This tutorial is best learned on the basis of JAVA
1. Interface
Kotlin's interface is almost identical to Java's
Define an interface:
interface Study{
fun readBooks()
fun doHomework()
}
Implement this interface with Student:
class Student(name : String , age : Int) : Study {
override fun readBooks() {
println(name + " is reading.")
}
override fun doHomework(){
println(name + " is doing homework.")
}
}
Those who are familiar with Java must specify that Java inherits from extends and implements interfaces from implements , while Kotlin uses : (colon) uniformly .
Now we can write the following code in the main() function to call the functions in these two interfaces
fun main() {
val student = Student("Jack",19)
doStudy(student)
}
fun doStudy(study : Study) {
study.readBooks()
study.doHomework()
}
But Kotlin also adds a feature:
Allows default implementations for functions defined in interfaces.
Not much to say, the code:
interface Study {
fun readBooks()
fun doHomework() {
println("do homework default implementation.")
}
}
At this time, you will find that the Student will only be required to implement the readBooks function.
Second, the visibility modifier of the function
Default modifiers:
Java : default
Kotlin : public
Kotlin abandons the default in Java and introduces a new concept: internal , which means that it is only visible to classes in the same module. protected is also different in Java and Kotlin, as shown in the following table:
Modifier | Java | Kotlin |
---|---|---|
public |
All classes are visible | All classes are visible (default) |
private | The current class is visible | The current class is visible |
protected | The current class, subclasses, and classes under the same package path are visible | The current class and subclasses are visible |
default | Classes under the same package path are visible (default) | none |
internal | none | Classes in the same module are visible |
If you like this series, please give it a thumbs up! Thanks for watching!
reference:
"The First Line of Code Android (Third Edition)" --- Guo Lin