kotlin-顶层函数和顶层属性

前言


学习是一点一滴的事急不得但是也不能不急

顶层函数

在kotlin 中我们可以将函数放在文件的最顶层 不用从属任何的一个数据类,这些放在文件顶部的函数依然数包内成员,如果想从包外访问他这要通过import语句来导入,好处在于通过使用一个import语句就能使用定义的这个函数

顶层属性

其实顶层函数和顶层属性的意义是差不多的,

@file:JvmName("XHMax")
package kotlin

/***
 * 这是一个声明顶层函数的方法
 */
fun max(a: Int, b: Int): Int {
    return if (a > b) a else b
}
/***
 * 定义顶层属性
 * 相当于 public static final String param = "this is a param"
 */
const val param:String  = "this is a param "
/***
 * 使用interface关键在声明接口
 *   - click() 为抽象方法 实现接口的类都必须重写这个抽象方法
 *   - 接口中可以添加一个默认的实现的方法 默认的方法是选择性重写的
 *
 */
interface Clickeable {
    fun click()
    fun showOff() = println("I m clickable")
}

interface Focusable {
    fun setFocus(b: Boolean) = println(" I m boolean method")
    fun showOff() = println("I m focusable")
}

class Button : Clickeable, Focusable {
    /***
     * 接口中的抽象方法是open的  可以通过显示的添加final 关键字
     * 来禁止重写
     */
    override fun click() {
        TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
    }

    /***
     * 接口实现的冲突的解决
     */
    override fun showOff() {
        super<Clickeable>.showOff()
        super<Focusable>.showOff()
    }


}

/***
 * 使用open修饰符修饰的类才是可以被继承的类
 */
open class RichButton : Clickeable {
    /***
     * 这个类重写了一个open 的方法 默认还是open的
     */
    override fun click() {
        TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
    }

    /***
     * 类中的方法默认是final 是不能被继承的
     */
    fun disable() {

    }

    /***
     * 使用open修饰符修饰的类是可以被重写的
     */
    open fun animate() {}
}

/***
 *   抽象类的声明使用的是 abstract 关键字
 */
abstract class Animated {
    /***
     * 抽象方法不能包含方法体  必须被重写
     */
    abstract fun animated()

    /***
     * 抽象类中的方法默认是final的  可以显示的指定为open
     */
    open fun stopAnimating() {

    }

    fun animatedTwice() {

    }
}

猜你喜欢

转载自blog.csdn.net/xh_ssh/article/details/80575560