当前位置:网站首页>Kotlin introductory notes (VI) interface and function visibility modifiers

Kotlin introductory notes (VI) interface and function visibility modifiers

2022-07-05 09:14:00 Meng Meng Mu Xi

Preface : This tutorial is best done with JAVA Study on the basis of

One 、 Interface

Kotlin Interface and Java Almost exactly the same

Define an interface :

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

use Student Implement this interface :

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

be familiar with Java The person must specify ,Java For inheritance of extends  , The interface is implemented with implements  , and Kotlin Unified use :  ( The colon ).

Now we can main() Function, write the following code 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()
}

however Kotlin Also added a function :

        Allows default implementation of functions defined in the interface .

Don't talk much , Code up :

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

  At this time, you will find ,Student Will only force the implementation of readBooks A function .

Two 、 Visibility modifier of function

Default modifier :

               Java :  default

               Kotlin : public

Kotlin Abandoned Java Medium default , Introduced a new concept :internal , Indicates that it is only visible to classes of the same module . protected stay Java And Kotlin It's different , See the following table for details :

Java And Kotlin Function visibility modifier comparison table
Modifier JavaKotlin

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 、 Subclass 、 Classes under the same package path are visible The current class 、 Subclasses are visible
default Classes under the same package path are visible ( Default ) nothing
internal nothing Class visible in the first mock exam module  

If you like this series , You might as well pay attention ! Thank you for watching !

Reference resources :

        《 First line of code Android ( The third edition )》   --- Guo Lin

原网站

版权声明
本文为[Meng Meng Mu Xi]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202140538292457.html