当前位置:网站首页>Androidkotlin comprehensive and detailed class usage grammar learning guide
Androidkotlin comprehensive and detailed class usage grammar learning guide
2022-06-23 23:22:00 【1024 Q】
Preface
1. Declaration of a class & Instantiation
2. Constructors
2.1 Primary constructor
2.2 The secondary constructor
3. Attributes of a class
4. Visibility modifier
5. Inherit & rewrite
6. Special class
6.1 Nested class ( Inner class )
6.2 Interface
6.3 Data class
6.4 Enumeration class
summary
PrefaceKotlin By Google Officially, Android First level programming language developed

today , I will focus on kotlin All the knowledge of the class in , The main contents are as follows :

// Format class Class name ( Parameter name 1: Parameter type , Parameter name 2: Parameter type ...){ // to do }// Example class User(userName: String, age: Int){ // to do }// Instantiation // Kotlin No, new keyword , So create an instance of the class directly ( No reference & Ginseng ):var user = User()var user = User("ABC" , 123)// Additional instructions :Kotlin Support default parameters // That is, you can call a function without specifying parameters , Then use the default function class User(userName: String = "hjc", age: Int = 26){ // to do }// When instantiating a class, no parameters are passed in ,userName Default = hjc,age Default = 26var user = User()// After setting the default value , If you don't want to use the default value, you can pass in the parameter when you create an instance var user = User("ABC" , 123)// notes : Named parameter if a default parameter precedes a parameter with no default value , The default value can only be used by calling the function with named parameters class User(userName: String = "hjc", age: Int){ // to do }var user = User(age = 26)For constructors ,Kotlin A class in can have a primary constructor & Multiple sub constructors , I'll explain in detail .
2. Constructors 2.1 Primary constructorPart of the class header = Follow the class name , use constructor keyword
Can't contain any code . The initialization code is placed in init Keyword as a prefix in the code block
class Class name constructor( Parameter name : Parameter type ){init { //... }}// Example class User constructor(userName: String) {init { //... }}// notes : If the main constructor has no comments / Visibility modifier , Omission constructor keyword class Class name ( Parameter name : Parameter type ){init { //... }}// Example class User (userName: String) {init { //... }}2.2 The secondary constructor Must be added constructor keyword
There can be multiple sub constructors in a class , The input parameters are different
// form constructor( Parameter name : Parameter type ) :{ The body of the function }// Example class User(userName: String) { // Primary constructor init { println(userName) } // The secondary constructor 1: It can be done by this Call the main constructor constructor() : this("hjc") // The secondary constructor 2: It can be done by this Call the main constructor constructor(age: Int) : this("hjc") { println(age) } // The secondary constructor 3: adopt this Call the main constructor constructor(sex: String, age: Int) : this("hjc") { println("$sex$age") }}// Instantiate the class User("hjc") // Call the main constructor User() // Call the secondary constructor 1User(2) // Call the secondary constructor 2User("male",26) // Call the secondary constructor 33. Attributes of a class Kotlin Can have properties : keyword var( Reading and writing ) / keyword val( read-only )
class User { var userName: String val sex: String = " male "}// Use attributes = name + quote User().sex // Use this property = Java Of getter Method User().userName = "hjc" // Set this property = Java Of setter Method 4. Visibility modifier 
Be similar to Java,Kotlin It's single inheritance = There is only one parent class
difference :Kotlin Use a colon “ : ” Inherit & Inheritance is not allowed by default ( If you want the class to be inheritable , need open Keywords )
// use open Keyword indicates that the class is allowed to be inherited open class Food // class Fruits Inheritance class Foodclass Fruits : Food()Override the method of the parent class for the child class , stay Kotlin in , Methods are also non rewritable by default
If a subclass wants to override a method in a parent class , You need to precede the method of the parent class with open keyword , Then add... Before the method overridden by the subclass override keyword
// Parent class // In the class & Methods are preceded by keywords open, In order to be inherited & Method rewriting open class Food { open fun banana() {}}// Subclass class Fruits : Food(){// Overriding the method of the parent class override fun banana() { super.banana() }}6. Special class Here are some special classes :
Nested class ( Inner class )
Interface
Data class
Enumeration class
6.1 Nested class ( Inner class )/** * 1. Nested class ( Inner class ) * identification : keyword inner * Use : Call nested classes through instances of external classes */ class User { var age: Int = 0 inner class UserName { }}var userName: User.UserName = User().UserName()6.2 Interface /** * 2. Interface * identification : keyword interface */// Statement interface A{}interface B{}// Method body // Methods in an interface can have a default method body , Methods with a default method body do not need to be overridden // The difference in Java:Java Methods in interfaces are not supported. Methods in interfaces are method bodies .interface UserImpl{ fun getName(): String // No default method body , Must be rewritten fun getAge(): Int{ // There is a default method body , Don't rewrite return 22 }}// Implementation interface UserImpl: Need to rewrite getName() & Don't rewrite getAge()class User :UserImpl{ override fun getName(): String { return "hjc" }}// Implementation interface : The colon :class Food : A, B {} // Kotlin It's more to achieve class Fruits: Food,A, B {} // Inherit + Implementation interface 6.3 Data class /** * 3. Data class * effect : Save the data * identification : keyword data */// Use : The following methods are automatically created when you create a class :// 1. getter/setter Method ;// 2. equals() / hashCode() Yes ;// 3. toString() : Output " Class name ( Parameters + Parameter values )";// 4. copy() function : Copy an object & Change some of its properties , But the rest remains the same // Example :// Statement 1 Data classes data class User(var userName: String, var age: Int)// copy Function USES var user = User("hjc",26)var user1 = user.copy(age = 30)// Output user1.toString(), The result is :User(userName=hjc,age=30)// Particular attention // 1. The main constructor must have at least one parameter , And the parameter must be marked val or var// 2. Data classes cannot be used open、abstract、sealed( Closed class )、inner identification 6.4 Enumeration class /** * 4. Enumeration class * identification : keyword enum */ // Definition enum class Color { RED, GREEN, BLUE}// Specify a value for the enumeration class enum class Color(rgb: Int) { RED(0xFF0000), GREEN(0x00FF00), BLUE(0x0000FF)}thus , About kotlin The introduction of class usage in Introductory Grammar is finished .
summaryThis paper gives a comprehensive introduction Kotlin Classes in introductory syntax
That's all Android Kotlin Details of the comprehensive and detailed class grammar learning guide , More about Android Kotlin For information about class syntax, please pay attention to other related articles on the software development network !
边栏推荐
- MySQL事務隔離
- Short video enters the hinterland of online music
- C# 读取内存条占用大小,硬盘占用大小
- Reconstruct the backbone of the supply chain and realize lean production in the LED lighting industry
- TDD开发模式流程推荐
- Tencent lightweight + pagoda building document online preview project kkfileview
- MySQL transaction isolation
- TDD development mode process recommendation
- C# Winform 自定义进度条ProgressBar
- pyspark on hpc
猜你喜欢

C#/VB. Net word to text

远程办公之:如何成为时间管理大师?| 社区征文
![[observation] Dell technology + Intel aoteng Technology: leading storage innovation with](/img/cf/3e3eb6389693667edad534b556c15c.png)
[observation] Dell technology + Intel aoteng Technology: leading storage innovation with "nanosecond speed"

Detailed quaternion

The technical design and practice of decrypting the red envelopes of Tiktok Spring Festival
PostgreSQL怎么创建分区表详解

Cause analysis and Countermeasures for FANUC robot srvo-050 collision detection alarm (available for personal test)

The Sandbox 与 BAYZ 达成合作,共同带动巴西的元宇宙发展

短视频挺进在线音乐腹地

C# 读取内存条占用大小,硬盘占用大小
随机推荐
C# Winform 自定义进度条ProgressBar
Zynq Ultrascale+ RF Data Coverter IP配置 - ADC
数据解读!理想L9冲刺「月销过万」,从BBA手中抢份额
TDP "spark" plan - the third phase of new recruitment is launched
kubernetes之常用核心资源对象
Can postman be integrated into Ci and CD pipelines for automated interface testing?
Trigger definition and syntax introduction in MySQL
Ambire 指南:Arbitrum 奥德赛活动开始!第一周——跨链桥
谈谈数字化转型晓知识
Flutter中的GetX状态管理用起来真的那么香吗?
[technical dry goods] the technical construction route and characteristics of zero trust in ant Office
评估和选择最佳学习模型的一些指标总结
Log4j has been exposed to a nuclear bomb level vulnerability, and the developer has fried the pot!
Cs5213 HDMI to VGA with audio signal output scheme
Notes to nodejs (III)
[js] remove the extra zero after the decimal point
What server is used for website construction? What is the price of the server
The national post office and other three departments: strengthen the security management of personal information related to postal express delivery, and promote the de identification technology of per
专业“搬砖”老司机总结的 12 条 SQL 优化方案,非常实用!
Ant group's self-developed tee technology has passed the national financial technology product certification