当前位置:网站首页>Kotlin basic definition class, initialization and inheritance
Kotlin basic definition class, initialization and inheritance
2022-06-13 06:24:00 【m0_ forty-seven million nine hundred and fourteen thousand one 】
One . Defining classes
1.field
For every attribute you define ,Kotlin There will be a field, One getter, And one. setter,field Used to store attribute data , You can't directly define field,Kotlin Will encapsulate field, Protect the data in it , Only exposed to getter and setter Use . Attribute getter Method determines how you read the property value , Each attribute has getter Method ,setter Method determines how you assign a value to an attribute , So only variable attributes can have setter Method , Even though Kotlin Will automatically provide the default getter and setter Method , But when you need to control how to read and write attribute data , You can also customize them .
class Player{
var name="XiaoHua"
get()=field.capitalize()
private set(value) {
field=value.trim()
}
var age=10
get() = field.absoluteValue
set(value) {
field=value.absoluteValue
}
}2. Compute properties
The calculated attributes are the same and have the same override get or set Operator to define , At this time field Not really .
class Player {
var calculateValue
get() = (1..10).shuffled().first()
}Two . initialization
1. Primary constructor
We are Player A main constructor is defined in the definition header of the class , The temporary variable used is Player Provide initial values for each attribute of the , And in the Kotlin in , For easy identification , Temporary variable ( Include parameters that are referenced only once ), Usually with Names that begin with an underscore are named .
class Player (
_name : String,
_age : Int,
_isNormal : Boolean
){
var name=_name
get()=field.capitalize()
private set(value) {
field=value.trim()
}
var age=_age
get() = field.absoluteValue
set(value) {
field=value.absoluteValue
}
var isNormal=_isNormal;
}2. Define properties in the main constructor
Kotlin Allows you to assign values without using temporary variables , Instead, you can use a definition to specify both parameters and class attributes , Usually , We prefer to define class attributes in this way , Because it will reduce duplication of code .
class Player2(
_name : String,
var age : Int,
var isNormal : Boolean
){
var name=_name
get()=field.capitalize()
set(value) {
field=value.capitalize()
}
}3. The secondary constructor
The secondary constructor corresponds to the primary constructor , We can Define multiple such constructors to configure different combinations of parameters , We can also use this constructor Initialization code .
class Player2(
_name : String,
var age : Int,
var isNormal : Boolean
){
var name=_name
get()=field.capitalize()
set(value) {
field=value.capitalize()
}
// Secondary constructor
constructor(name:String):this(name,age=100,isNormal=true)
// This constructor initializes
constructor(name:String,age:Int):this(name,age=100,isNormal=true){
this.name=name.capitalize()
}
}
4. Default parameters
When defining a constructor , You can specify default values for constructor parameters , If the user does not provide a value parameter when calling , Just use this default
class Player3(
_name : String,
var age : Int=20,
var isNormal : Boolean
){
var name=_name
get()=field.capitalize()
set(value) {
field=value.capitalize()
}
}5. initialization
The initialization block can set variables or values , And perform effectiveness checks , For example, check whether the value given to a constructor is valid , The initialization code is executed when the class instance is constructed .
// Static code block
init {
// Not meeting the conditions Throw exceptions
require(age>0){ "age muse be positive" }
require(name.isNotBlank()){"player muse have"}
}6. Initialization sequence
1. Properties declared in the main constructor
2. Member property assignment
3.init Attribute assignment and function call in initialization block
4. Attribute assignment and function call in the secondary constructor

7. Delay initialization
Use lateinit Keyword is equivalent to making a convention : Be responsible for initializing before reusing it
As long as you can't confirm lateinit Whether the variable is initialized , It can be executed isInitialized Check
class Player4 {
// Delay initialization
lateinit var equipment :String
fun ready(){
equipment="aaaa"
}
fun battle(){
// Check for initialization
if (::equipment.isInitialized){
print(equipment)
}
}
}
fun main() {
val player4 = Player4()
player4.ready()
player4.battle()
}8. Lazy initialization
Delaying comfort is not the only way to delay initialization , You can also temporarily not initialize a variable , Until you use it for the first time , This is called lazy initialization .
class Player5(_name:String) {
var name=_name
val config by lazy { loadConfig() }
private fun loadConfig():String{
print("loading.....")
return "Asdsad"
}
}
fun main() {
val p = Player5("xiaohua")
print(p.config)
}9. Initialize trap
1.
When using initialization blocks , Sequence is very important , You must ensure that all attributes in the block have been initialized .

2.
There is no problem compiling this code , Because the compiler sees name The attribute is already in init Block is initialized , But as soon as the code runs , Will throw a null pointer exception , because name Property has not been assigned ,firstLetter The function applies it .
class Player7() {
val name:String
private fun firstLetter()=name[0]
init {
println(firstLetter())
name="XiaoHua"
}
}
3.
Because the compiler sees that all properties are initialized , So code compilation is OK , But the result is null, The problem is
initPlayerName Function initialization playerName when ,name Property is not complete yet .
class Player8(_name: String) {
val playerName:String=initPlayerName();
val name:String=_name
private fun initPlayerName()=name;
}3、 ... and . Inherit
1. Inherit
Classes are closed by default , To make a class open inheritance , You have to use open Keyword decorates it .
// Parent class flag open
open class Product (val name:String){
fun description()="Product: $name"
//open The methods to be inherited also need
open fun load()="Nothing..."
}
class LuxuryProduct :Product("Luxury"){
}
2. function overloading
The function of the parent class should also be expressed as open Keyword modification , Subclasses can override it .
// Parent class flag open
open class Product (val name:String){
fun description()="Product: $name"
//open The methods to be inherited also need
open fun load()="Nothing..."
}
class LuxuryProduct :Product("Luxury"){
//override rewrite
override fun load()="LuxuryProduct loading..."
}
3. Type testing
Kotlin Of is Operator can check the property type
// Parent class flag open
open class Product (val name:String){
fun description()="Product: $name"
//open The methods to be inherited also need
open fun load()="Nothing..."
}
class LuxuryProduct :Product("Luxury"){
//override rewrite
override fun load()="LuxuryProduct loading..."
fun special()="aaaaaaaaaaaaaaaaaa"
}
fun main() {
//kotlin polymorphic
val luxuryProduct:Product = LuxuryProduct()
print(luxuryProduct.name)
// Judge Type checking
print(luxuryProduct is Product)
print(luxuryProduct is LuxuryProduct)
print(luxuryProduct is File)
}4. Type conversion
as Operator declaration , This is a type conversion
// Parent class flag open
open class Product (val name:String){
fun description()="Product: $name"
//open The methods to be inherited also need
open fun load()="Nothing..."
}
class LuxuryProduct :Product("Luxury"){
//override rewrite
override fun load()="LuxuryProduct loading..."
fun special()="aaaaaaaaaaaaaaaaaa"
}
fun main() {
//kotlin polymorphic
val luxuryProduct:Product = LuxuryProduct()
print(luxuryProduct.name)
// This shows that the type of a class can only be converted once After that, you don't have to turn
print((luxuryProduct as LuxuryProduct).special() )
print(luxuryProduct.special() )
}
5. Intelligent type conversion
Kotlin Compilers are smart , You have to be sure any is The parent condition check is true , He will any As a subclass
Type treatment , therefore , The compiler runs you directly without type conversion .
// Parent class flag open
open class Product (val name:String){
fun description()="Product: $name"
//open The methods to be inherited also need
open fun load()="Nothing..."
}
class LuxuryProduct :Product("Luxury"){
//override rewrite
override fun load()="LuxuryProduct loading..."
fun special()="aaaaaaaaaaaaaaaaaa"
}
fun main() {
// First judge
if (luxuryProduct is LuxuryProduct){
// This is because polymorphism is used The created object points to the parent class reference The parent class cannot call the methods of the child class So we have to change
print(luxuryProduct.special() )
}
}6.Kotlin level
stay Kotlin Each class in the inherits a class called Any Superclass of ( similar java Medium Object)
边栏推荐
- 微信小程序:全局状态变量的使用
- 《MATLAB 神经网络43个案例分析》:第10章 离散Hopfield神经网络的分类——高校科研能力评价
- MFS details (vii) - - MFS client and Web Monitoring installation configuration
- Multiple reception occurs in the uniapp message delivery
- [var const let differences]
- 【DP之01背包】
- Wechat applet (pull-down refresh data) novice to
- 超有范的 logo 在线设计制作工具
- SSM框架整合--->简单后台管理
- JVM Foundation
猜你喜欢

Uniapp secondary encapsulates uview components, and the parent component controls display and hiding

【DP之01背包】

js将文本转成语言播放

Fichier local second Search Tool everything

USB debugging assistant (20191028)

欧姆龙平替国产大货—JY-V640半导体晶元盒读写器

Basic knowledge of knowledge map

Relationship between fragment lifecycle and activity

华为开发者认证与DevEco Studio编译器下载
![[one · data 𞓜 simple implementation of the leading two-way circular linked list]](/img/a2/08f55012cd815190db76237f013961.png)
[one · data 𞓜 simple implementation of the leading two-way circular linked list]
随机推荐
The title of the WebView page will be displayed in the top navigation bar of the app. How to customize
USB status error and its cause (error code)
端午安康,使用祝福话语生成词云吧
Wechat applet (function transfer parameters, transfer multiple parameters, page Jump)
【新手上路常见问答】关于技术管理
Waterfall flow layout of uni app Homepage
MFS details (vii) - - MFS client and Web Monitoring installation configuration
Uni app provincial and urban linkage
MFS详解(六)——MFS Chunk Server服务器安装与配置
MFS详解(七)——MFS客户端与web监控安装配置
[JS] handwriting call(), apply(), bind()
Uniapp (upload local pictures, preview pictures, convert Base64 format, upload audio files)
[JS] array de duplication
RFID process management solution for electroplating fixture
【js】var、let、const
动态链接库嵌套样例
Basic knowledge of knowledge map
View绘制整体流程简析
[one · data 𞓜 simple implementation of the leading two-way circular linked list]
本地文件秒搜工具 Everything