Kotlin learning - interface + visible modifier

Interface definition

Interface definitions in kotlin and Java are similar:

interface Study {
    
    
    fun doHomework()
    fun readBooks()
}

interface implementation

To implement the Study interface in Student, all unimplemented functions declared in Study need to be implemented.

class Student(name: String,  age: Int) : Person(name, age), Study{
    
    
    override fun doHomework() {
    
    
        println("$name is doing homework")
    }
    override fun readBooks() {
    
    
        println("$name is reading homework")
    }
}

The following is used for interface polymorphism:

fun main() {
    
    
    val student = Student("lucy", 19)
    //student.doHomework()
    study(student)
}

fun study(study: Study) {
    
    
    study.doHomework()
}

//结果:lucy is doing homework

Interface function implementation

Kotlin allows default implementations for functions defined in interfaces.

interface Study {
    
    
    fun doHomework(){
    
    
        println("do homework default implementation")
    }
    fun readBooks()
}

Since doHomework has a default implementation, the interface implementation class will no longer be required to implement it.

class Student(name: String,  age: Int) : Person(name, age), Study{
    
    
    override fun readBooks() {
    
    
        println("$name is reading homework")
    }
}

Run the following program:

fun main() {
    
    
    val student = Student("lucy", 19)
    student.doHomework()
}

//结果:do homework default implementation

visible modifier

Below is the range and comparison of visible modifiers in Java and Kotlin.

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

Guess you like

Origin blog.csdn.net/kongqwesd12/article/details/131224373