kotlin获取属性_Kotlin程序| 属性获取器和设置器方法的示例
kotlin獲取屬性
屬性獲取器和設(shè)置器方法 (Properties Getter and Setter Methods)
Variable having a class-level scope, declared inside the class body but outside the functions called property.
具有類(lèi)級(jí)別范圍的變量,在類(lèi)主體內(nèi)部但在稱(chēng)為屬性的函數(shù)外部聲明。
Property can be declared with var(mutable) and val (read-only).
可以使用var(mutable)和val(只讀)聲明屬性。
var/val <propertyName>: <PropertyType> = <property_initializer> [<getter>] [<setter>]property_initializer, getter, and Setter are optional.
property_initializer,getter和Setter是可選的。
Getter and Setter Auto-Generated into the code.
Getter和Setter自動(dòng)生成到代碼中。
Getter is used to get the value of properties and setter is used to set value of properties.
Getter用于獲取屬性值,而setter用于設(shè)置屬性值。
val(read-only) type property does not allow setter.
val(只讀)類(lèi)型屬性不允許使用setter。
If we don't want public access of setter than declare it private.
如果我們不希望公開(kāi)訪問(wèn)setter,則將其聲明為私有。
var name:String private set
程序以演示Kotlin中的屬性Getter和Setter方法的示例 (Program to demonstrate the example of Properties Getter and Setter Methods in Kotlin)
package com.includehelp// Declare class, class America{// Declare property with initial valuevar city:String = "NewYork"// Auto Generated getter and setter }// Declare class, class India{// Declare property with initial valuevar city:String = "Delhi"// define optional getter and setterget() = field // Getterset(value) { // Setterfield=value} }// Declare class, define optional getter and setter class China{// Declare property with initial valuevar city:String = "Wuhan"// private setter, cant set value from outside the classprivate set// member function to set propertyfun setCity(city:String){this.city=city}}// declare class, with customized getter and setter class Japan{// Declare property with initial valuevar city:String = "Tokyo"// Getter of propertyget() = field.toUpperCase()//setter of Propertyset(value) {field="Modern City $value"} }// Main function, entry Point of Program fun main(){// create Instanceval america=America()america.city="Alsakaaa" // access setterprintln("America : ${america.city}") // access getter// create Instanceval india=India()india.city="Mumbai" // access setterprintln("India : ${india.city}") // access getter// create Instanceval china=China()// Try to access private setter, leads to compile time error// china.city="Beijing"// Set City by calling member functionchina.setCity("Beijing")println("China : ${china.city}") // access getter// create Instanceval japan=Japan()india.city="Quoto" // access setterprintln("Japan : ${india.city}") // access getter }Output:
輸出:
America : Alsakaaa India : Mumbai China : Beijing Japan : Quoto翻譯自: https://www.includehelp.com/kotlin/example-of-properties-getter-and-setter-methods.aspx
kotlin獲取屬性
總結(jié)
以上是生活随笔為你收集整理的kotlin获取属性_Kotlin程序| 属性获取器和设置器方法的示例的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 工作总结:日志打印的15个建议
- 下一篇: c构造函数和析构函数_C ++构造函数,