What is the difference between 'open' and 'public' in Kotlin?

后端 未结 6 1886
面向向阳花
面向向阳花 2021-01-03 19:26

I am new to Kotlin and I am confused between open and public keywords. Could anyone please tell me the difference between those keywords?

6条回答
  •  -上瘾入骨i
    2021-01-03 19:56

    open is opposite to Final in java. If the class is not 'open', it can't be inherited.

    class First{}
    class Second:First(){}  // Not allowed. Since 'First' is Final(as in Java) by default. Unless marked "open" it can't be inherited 
    

    Don't get confused with open and public. public is a visibility modifier

    class Third{}  // By default this is public
    private class Fourth{}
    class Fifth{
        val third = Third() // No issues
        val fourth = Fourth() // Can't access because Fourth is private
    }
    

提交回复
热议问题