当前位置:网站首页>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)
边栏推荐
- Download and installation of universal player potplayer, live stream m3u8 import
- 《MATLAB 神经网络43个案例分析》:第11章 连续Hopfield神经网络的优化——旅行商问题优化计算
- JS to realize bidirectional data binding
- 动态链接库嵌套样例
- 微信小程序:全局状态变量的使用
- Rk3399 hid gadget configuration
- Wechat applet development (requesting background data and encapsulating request function)
- MFS details (vii) - - MFS client and Web Monitoring installation configuration
- MFS详解(五)——MFS元数据日志服务器安装与配置
- Solution: vscode open file will always overwrite the last opened label
猜你喜欢

JS convert text to language for playback

超有范的 logo 在线设计制作工具

Analysis of 43 cases of MATLAB neural network: Chapter 10 classification of discrete Hopfield Neural Network -- evaluation of scientific research ability of colleges and Universities

Echart histogram: echart implements stacked histogram

Rk3399 hid gadget configuration

【新手上路常见问答】一步一步理解程序设计

You should consider upgrading via

Free screen recording software captura download and installation

本地文件秒搜工具 Everything

Echart柱状图:堆叠柱状图显示value
随机推荐
Echart柱状图:echart实现堆叠柱状图
【新手上路常见问答】关于技术管理
RN Metro packaging process and sentry code monitoring
RFID process management solution for electroplating fixture
自定义View
Applet Use of spaces
Applet pull-up loading data
自定义View —— 可伸展的CollapsExpendView
Echart line chart: different colors are displayed when the names of multiple line charts are the same
The boys x pubgmobile linkage is coming! Check out the latest game posters
Not in the following list of legal domain names, wechat applet solution
【2022高考季】作为一个过来人想说的话
MFS详解(五)——MFS元数据日志服务器安装与配置
免费录屏软件Captura下载安装
The jadx decompiler can decompile jars and apks
A brief analysis of the overall process of view drawing
Uniapp hides the scroll bar of scroll view
Applet export (use) public function, public data
Fidde breakpoint interception
USB status error and its cause (error code)