本文共 2436 字,大约阅读时间需要 8 分钟。
kotlin 构造函数
A Kotlin class have Primary constructor and one or more Secondary constructor.
Kotlin类具有Primary构造函数和一个或多个Secondary构造函数。
In Kotlin, Primary Constructor is the Part of Class Header.
在Kotlin中,主要构造函数是类标题的一部分。
Syntax:
句法:
classconstructor( ){ // Class Body}
The default visibility of the constructor will be public.
构造函数的默认可见性将是public。
Parameter of the primary constructor can be used in property initializer, declared in the class body.
可以在类体内声明的属性初始化程序中使用主构造函数的参数。
// Declare Class, with Primary Constructor keyword, // with one Parameterclass Dog constructor(name:String){ // Used Constructor Parameter to initialize property // in class body // String? for nullable property, // so property also contain null private var name:String?=name fun getDogName(): String?{ return name }}/* A) Constructor Keyword can be omitted if constructor does not have annotations and visibility modifiers.*/// Declare class, omitted Constructor Keywordclass Horse (name:String){ // Used Constructor Parameter to // initialize property in class body private var name:String =name.toUpperCase() fun getHorseName(): String?{ return name }}/* A) Kotlin has concise Syntax to declaring property and initialize them from primary constructor. class Employee(var empName:String, val salary:Int) B) same way as regular properties declaration, properties declare in primary constructor can be var (mutable) or val (immutable) */ // Declare class, Properties declare in primary constructorclass Cat(private var name:String, private val age:Int){ fun setCatName(name:String){ this.name =name } fun printData(){ println("Name : $name and Age : $age") }}// Main Function, entry Point of Programfun main(args:Array){ // Create Dog Class Object val dog = Dog("tommy") println("Dog Name : ${dog.getDogName()}") // Create Horse Class object val horse =Horse("Chetak") println("Horse Name : ${horse.getHorseName()}") // Create Cat Class object val cat = Cat("Katrina",32) cat.printData() cat.setCatName("Micy") cat.printData()}
Output:
输出:
Dog Name : tommyHorse Name : CHETAKName : Katrina and Age : 32Name : Micy and Age : 32
翻译自:
kotlin 构造函数
转载地址:http://kexzd.baihongyu.com/