日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

kotlin 构造函数_Kotlin程序| 主要构造函数示例

發布時間:2023/12/1 编程问答 32 豆豆
生活随笔 收集整理的這篇文章主要介紹了 kotlin 构造函数_Kotlin程序| 主要构造函数示例 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

kotlin 構造函數

主要建設者 (Primary Constructor)

  • 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:

    句法:

    class <Class Name> constructor(<optional Parameters>){// 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.

    可以在類體內聲明的屬性初始化程序中使用主構造函數的參數。

演示Kotlin中主要構造函數示例的程序 (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 構造函數

總結

以上是生活随笔為你收集整理的kotlin 构造函数_Kotlin程序| 主要构造函数示例的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。