Kotlin笔记-类

版权声明:本文为博主原创文章,转载请注明出处。 https://blog.csdn.net/lylodyf/article/details/80978949

类修饰符

// 属性修饰符
annotation  //注解类
abstract   //抽象类
final     //类不可继承,默认属性
enum     //枚举类
open    //类可继承,类默认是final的

// 访问权限修饰符
private   //仅在同一个文件中可见
protected //同一个文件中或子类可见
public    //所有调用的地方都可见
internal  //同一个模块中可见

类定义

class Person(name : String, age : int) {
} 

翻译成java为:

final public class Person {
    public Person(String name, int age){
    }
}

构造函数

当Kotlin中的类需要构造函数时,可以有一个主构造函数和多个次构造函数,可以没有次构造函数。主构造函数在类名后

//常规用法
class Person(name: String) {
}

当主构造函数有注解或者可见性修饰符,需加 constructor 关键字。注意默认是final类型,需要继承则指明open

open class Personpublic public @Inject constructor(name: String){
}

次级构造函数

如果类有一个主构造函数(无论有无参数),每个次构造函数需要直接或间接委托给主构造函数,用this关键字
次构造函数不能有声明 val 或 var ,比如下面是错误的:

class  Person(var name: String) {
    constructor(var name:String,var age:Int):this(name){

    }
}

正确的方式:

class Person(var name: String) {

    constructor(name: String, age: Int) : this(name) {

    }
}
  • 当没有主构造函数时:
class Child {
    constructor(father: String) {

    }

    constructor(age: Int) {

    }

//    constructor(father: String, mother: String) {
//        
//    }
    constructor(father: String, mother: String):this(father) {

    }
}

初始化

因为kotlin中的类定义同时也是构造函数,这个时候是不能进行操作的,所以kotlin增加了一个新的关键字init用来处理类的初始化问题,init模块中的内容可以直接使用构造函数的参数。

class Person(name : Stringage : int){
    init{
        // to do something
    }
}

参数默认值

kotlin中支持类定义的时候,参数可以设置默认值。

// 含有默认值的参数,可以不传,也就是说ParentClass("xiaoming", 22, 1)和ParentClass("xiaoming", 22)这两种调用方式都是可以的
constructor(name : String, age : Int, sex : Int = 0) : this(name) {
    log("This is --> secondry constructor, a=${++a}, age=$age, sex=$sex")
}

猜你喜欢

转载自blog.csdn.net/lylodyf/article/details/80978949