当前位置:网站首页>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 !
边栏推荐
- Production of labels for table products
- Detailed process of deploying redis cluster and micro service project in docker
- C WinForm custom progress bar ProgressBar
- Unknown character set index for field ‘255‘ received from server.
- The sandbox and bayz have reached cooperation to jointly drive the development of metauniverse in Brazil
- 抖音支付十万级 TPS 流量发券实践
- Website construction column setting form which website construction company is better
- 短视频挺进在线音乐腹地
- What is the development prospect of face recognition technology?
- How PostgreSQL creates partition tables
猜你喜欢

Chaos engineering, learn about it

远程办公之:如何成为时间管理大师?| 社区征文
How PostgreSQL creates partition tables
PostgreSQL怎么创建分区表详解

The sandbox and bayz have reached cooperation to jointly drive the development of metauniverse in Brazil

WebService client request failed can not create a secure xmlinputfactory

C# 读取内存条占用大小,硬盘占用大小

【技术干货】蚂蚁办公零信任的技术建设路线与特点

Generate post order traversal according to pre order traversal and mid order traversal

浩哥的博客之路
随机推荐
Detailed explanation of MySQL database configuration information viewing and modification methods
Isolement des transactions MySQL
短视频挺进在线音乐腹地
Practice of issuing vouchers for Tiktok payment of 100000 TPS traffic
Cs5213 HDMI to VGA with audio signal output scheme
TDD开发模式流程推荐
The fortress computer is connected to the server normally, but what's wrong with the black screen? What should I do?
go语言学习
AIX系统月维护查什么(二)
Cause analysis and Countermeasures for FANUC robot srvo-050 collision detection alarm (available for personal test)
Face and lining of fresh food pre storage
HAOGE's blog Road
光大期货安全吗?开户需要什么东西?
Data interpretation! Ideal L9 sprints to "sell more than 10000 yuan a month" to grab share from BBA
开发协同,高效管理 | 社区征文
Go language core 36 lectures (go language practice and application 23) -- learning notes
新股民怎样炒股票开户?在线开户安全么?
The principle of async and await
[observation] Dell technology + Intel aoteng Technology: leading storage innovation with "nanosecond speed"
[design] 1359- how umi3 implements plug-in architecture