当前位置:网站首页>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 !
边栏推荐
- Website construction is not set to inherit the superior column. How to find a website construction company
- Data interpretation! Ideal L9 sprints to "sell more than 10000 yuan a month" to grab share from BBA
- Application of clock synchronization system in banking system
- Mysql中的触发器定义及语法介绍
- Notes to nodejs (III)
- Reconstruct the backbone of the supply chain and realize lean production in the LED lighting industry
- HDLBits->Circuits->Arithmetic Circuitd->3-bit binary adder
- Operation and maintenance failure experience sharing
- MySQL事務隔離
- What is the development prospect of face recognition technology?
猜你喜欢

Summary of some indicators for evaluating and selecting the best learning model

谈谈数字化转型晓知识
AndroidKotlin全面详细类使用语法学习指南

Practice of issuing vouchers for Tiktok payment of 100000 TPS traffic

Detailed quaternion

CS5213 HDMI转VGA带音频信号输出方案
Detailed usage of exists in SQL statements
MySQL导致索引失效的几种情况

国家邮政局等三部门:加强涉邮政快递个人信息安全治理,推行隐私面单、虚拟号码等个人信息去标识化技术

Section 30 high availability (HA) configuration case of Tianrongxin topgate firewall
随机推荐
How does the fortress connection key server associate with the server host?
C# Winform 自定义进度条ProgressBar
Consequences of website construction without SSL authentication are websites without SSL authentication reliable
Go deep: the evolution of garbage collection
How PostgreSQL creates partition tables
专业“搬砖”老司机总结的 12 条 SQL 优化方案,非常实用!
How to use data warehouse to create time series
go语言学习
How to connect the fortress machine to the new server? What can I do if there is a problem with the fortress machine?
C# 读取内存条占用大小,硬盘占用大小
2022 cloud consulting technology series storage & CDN special sharing meeting
Notes to nodejs (III)
SQL Server Common SQL
微信视频号如何用 PC 电脑做直播?
What is the development prospect of face recognition technology?
谈谈数字化转型晓知识
How to judge the video frame type in h265 in golang development
TDP "spark" plan - the third phase of new recruitment is launched
Ant won the finqa competition champion and made a breakthrough in AI technology of long text numerical reasoning
Detailed process of deploying redis cluster and micro service project in docker