kotlin 构造函数_Kotlin程序| 主要构造函数示例
kotlin 構造函數(shù)
主要建設者 (Primary Constructor)
A Kotlin class have Primary constructor and one or more Secondary constructor.
Kotlin類具有Primary構造函數(shù)和一個或多個Secondary構造函數(shù)。
In Kotlin, Primary Constructor is the Part of Class Header.
在Kotlin中,主要構造函數(shù)是類標題的一部分。
Syntax:
句法:
class <Class Name> constructor(<optional Parameters>){// Class Body }The default visibility of the constructor will be public.
構造函數(shù)的默認可見性將是public。
Parameter of the primary constructor can be used in property initializer, declared in the class body.
可以在類體內(nèi)聲明的屬性初始化程序中使用主構造函數(shù)的參數(shù)。
演示Kotlin中主要構造函數(shù)示例的程序 (Program to demonstrate the example of Primary Constructor in Kotlin)
// Declare Class, with Primary Constructor keyword, // with one Parameter class Dog constructor(name:String){// Used Constructor Parameter to initialize property// in class body// String? for nullable property, // so property also contain nullprivate var name:String?=namefun getDogName(): String?{return name} }/*A) Constructor Keyword can be omitted if constructor does not have annotations and visibility modifiers. */ // Declare class, omitted Constructor Keyword class Horse (name:String){// Used Constructor Parameter to // initialize property in class bodyprivate 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 constructor class 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 Program fun main(args:Array<String>){// Create Dog Class Objectval dog = Dog("tommy")println("Dog Name : ${dog.getDogName()}")// Create Horse Class objectval horse =Horse("Chetak")println("Horse Name : ${horse.getHorseName()}")// Create Cat Class objectval cat = Cat("Katrina",32)cat.printData()cat.setCatName("Micy")cat.printData() }Output:
輸出:
Dog Name : tommy Horse Name : CHETAK Name : Katrina and Age : 32 Name : Micy and Age : 32翻譯自: https://www.includehelp.com/kotlin/example-of-primary-constructor.aspx
kotlin 構造函數(shù)
總結
以上是生活随笔為你收集整理的kotlin 构造函数_Kotlin程序| 主要构造函数示例的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 汽车首付多少钱啊?
- 下一篇: dbms支持哪几种数据模型_DBMS中不