失眠网,内容丰富有趣,生活中的好帮手!
失眠网 > kotlin 构造函数_Kotlin程序| 主要构造函数示例

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

时间:2022-02-20 12:19:14

相关推荐

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 Parameterclass 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 Keywordclass 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 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<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 : tommyHorse Name : CHETAKName : Katrina and Age : 32Name : Micy and Age : 32

翻译自: /kotlin/example-of-primary-constructor.aspx

kotlin 构造函数

如果觉得《kotlin 构造函数_Kotlin程序| 主要构造函数示例》对你有帮助,请点赞、收藏,并留下你的观点哦!

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。