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

后端 未结 6 1908
面向向阳花
面向向阳花 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条回答
  •  Happy的楠姐
    2021-01-03 19:57

    I put here just for my memo, maybe useful for someone else :

    open class in kotlin means that a class can be inherited because by default they are not:

     class Car{....}
     class Supercar:Car{....} : // give an error
    
     open Car2{....}
     class Supercar:Car2{....} : // ok
    

    public class in Java is about the visibility of class (nothing to do with inheritance : unless a class in java is final, it can be inherited by default). In kotlin all the class are public by default.

    open method in kotlin means that the method can be overridden, because by default they are not. Instead in Java all the methods can be overridden by default

    The method of an open class cannot be overridden by default as usual (doesn't matter if the class is open), they must be declared that they can be overridden :

     open class Car{
        fun steering{...}
     }
     class Supercar:Car{
        override fun steering {...}  // give an error
     } 
    
     open class Car2{
        open fun steering{...}
     }
     class Supercar:Car2{
        override fun steering {...}  // ok
     }
    

    for more details : https://kotlinlang.org/docs/reference/classes.html

提交回复
热议问题