当前位置:网站首页>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)
边栏推荐
- 二分查找
- Detailed explanation of PHP distributed transaction principle
- Analysis of 43 cases of MATLAB neural network: Chapter 11 optimization of continuous Hopfield Neural Network -- optimization calculation of traveling salesman problem
- 端午安康,使用祝福话语生成词云吧
- 347. top k high frequency elements heap sort + bucket sort +map
- js将文本转成语言播放
- Cross process two-way communication using messenger
- How to view APK version number from apk
- Download and installation of universal player potplayer, live stream m3u8 import
- ADB shell content command debug database
猜你喜欢
1+1 > 2, share creators can help you achieve
Echart矩形树图:简单实现矩形树图
AI实现亲人“复活”|老照片修复|老照片上色,免费APP推荐
SSM framework integration -- > simple background management
【DP之01背包】
Recommend a capacity expansion tool to completely solve the problem of insufficient disk space in Disk C and other disks
AI realizes "Resurrection" of relatives | old photo repair | old photo coloring, recommended by free app
【新手上路常见问答】一步一步理解程序设计
JVM基础
pthon 执行 pip 指令报错 You should consider upgrading via ...
随机推荐
Rk3399 hid gadget configuration
SSM框架整合--->简单后台管理
Dynamic link library nesting example
端午安康,使用祝福话语生成词云吧
自定义View
RN Metro packaging process and sentry code monitoring
MFS详解(六)——MFS Chunk Server服务器安装与配置
[var const let differences]
线程相关点
Applet export (use) public function, public data
You should consider upgrading via
无刷直流电机矢量控制(四):基于滑模观测器的无传感器控制
微信小程序:点击事件获取当前设备信息(基础)
Learning records countless questions (JS)
Echart矩形树图:简单实现矩形树图
[DP 01 backpack]
Echart rectangular tree diagram: simple implementation of rectangular tree diagram
The title of the WebView page will be displayed in the top navigation bar of the app. How to customize
Echart histogram: echart implements stacked histogram
ADB shell CMD overlay debugging command facilitates viewing system framework character resource values