Kotlin in Android cultivation manual - [class and object], [Get and Set], [inheritance], [interface], [abstract class / nested class / inner class], [data class] and [generic]

Posted by futurshox on Thu, 30 Dec 2021 05:07:46 +0100

My flag is still standing here. Do you see, my spear is still sharp, but I can't wave it for you anymore, so I build a high wall, wait, wait, the moment I unload it for you.

Sharing of previous articles

Click jump = > stay up late and fight Android again from bronze to King - development efficiency plug-in
Click jump = > unity particle special effects series - Tornado preform is ready, and the unitypackage package can be used directly!
Click jump = > my sister asked me to unlock the new skills of dolls: FairyGUI realizes List nesting List / Three-dimensional Gallery in Unity, and plays with flowers
Click jump = > unity novice must have 5 treasure plug-ins - the latest version of white whoring worth thousands of yuan
Summary of introduction to the C# basics of exploding the liver [suggestions collection]
Android cultivation manual - playing with TextView, I didn't expect so many attributes
[ten thousand words] stay up late to practice Android Studio skills and get a quick salary increase [recommended collection]
Learning from beginning to end of Android cultivation manual Kotlin [complete]

This article is about 7000 words. It takes 16 minutes for novices to read and 5 minutes for review

👉 About the author

As we all know, life is a long process, constantly overcoming difficulties and constantly reflecting on the process of progress. In this process, there will be a lot of questions and thoughts about life, so I decided to share all my thoughts, experiences and stories in order to find resonance!!!
Focus on Android/Unity and various game development skills, as well as various resource sharing (website, tools, materials, source code, games, etc.)
If there is any need to welcome private self, exchange group, so that learning is no longer lonely.

👉 premise

This is Xiaokong's Android series. Welcome to taste it.

👉 Practice process

😜 [classes and objects]

Class is also created using the [class] keyword

class Entity {
     var name: String? = null
     var urlJUEJIIN: String? = null
     var urlCSDN: String? = null
     var urlList: List<String>? = null
}

The new keyword is not used during initialization

var tempEntity = Entity() / / equivalent to java's Entity tempEntiy=new Entity();

tempEntity.name = "this is my name" / / click the attributes in it

In Java, there can be multiple constructors, all of which are class names. There are some differences in Kotlin

  1. There is a distinction between primary and secondary constructors
  2. Primary and secondary constructors are recommended to exist separately, because they require special processing to exist at the same time
  3. There is an initialization function. As long as this class is created, the contents of the initialization function must be executed

How to modify the access rights of constructors?

The secondary constructor is written directly in front of the function, and the primary constructor is written before the class name of the function

class Entity {
    init {
        Log.e("TAG,", "Class. The keyword is init-Built in system ")
    }

    var name: String? = null
    var urlJUEJIIN: String? = null
    var urlCSDN: String? = null
    var urlList: List<String>? = null

    constructor() {

    }

    private constructor(name: String) {

    }

    //Secondary constructors with different parameters
    constructor(name: String, age: Int) {
        Log.e("TAG,", "Constructor executed $name===$age")
    }
}



//These are two classes. Don't confuse them in the two files

//This is the main constructor, which uses the keyword constructor directly after the class name
class Person private constructor(name: String, age: String) {
    init {

    }

    //Special treatment: if the primary structure and secondary structure exist at the same time -- the parameter content of the primary structure must be included
    constructor(name: String, age: String, height: Int) : this(name, age) {

    }
}

//2021-10-14 14:52:59.468 10639-10639/cn.appstudy E/TAG: the initialization function of the class. The keyword is built-in in init system
//2021-10-14 14:52:59.468 10639-10639/cn.appstudy E/TAG,: constructor test executed = = = 20

So what if class inheritance?

If the parent class has a constructor, the child class must also have at least one. If it is insufficient, the editor will prompt a warning

The method of using the parent class also uses the [super] keyword, and the parent class needs the [open] keyword

open class Entity {
    init {
        Log.e("TAG,", "Class. The keyword is init-Built in system ")
    }

    constructor() {

    }

    constructor(name: String) {

    }

    //Secondary constructors with different parameters
    constructor(name: String, age: Int) {
        Log.e("TAG,", "The parent constructor was executed $name===$age")
    }
}

 
class EntityTwo : Entity {
    constructor() {

    }

    constructor(name: String) : this(name, 0) {

    }

    //Secondary constructors with different parameters
    constructor(name: String, age: Int) : super(name, age) {
        Log.e("TAG,", "Subclass constructor executed $name===$age")
    }
}

😜 [Get and Set]

In fact, after Kotlin declares the entity class, the variables in it have set and get attribute functions by default. Unless you want special business content.

For example, set needs to perform other business processing in combination with the project, and the same is true for get.

[filed] is a built-in keyword in the system and is regarded as an intermediate variable

Except these

var name: String? = null
        set(value) { //Name yourself at will
            field = value  //This field is built-in in the system and used in get
        }
        get() {
            return field + "This is a return"
        }
var urlJUEJIIN: String? = null
        get() =field+"This is only get"
var urlCSDN: String? = null
var urlList: List<String>? = null

😜 [succession]

In Java, it can be said that all classes inherit from Object, while in Kotlin, it can be said that all classes inherit from Any class.

Inherit and use the keyword [extends] in Java, and use [:] (English colon) in Kotlin

In addition, whether it is method rewriting or attribute variable rewriting, the [override] keyword is added in front, which is the same as Java

class EntityTwo : Entity {
    constructor() {

    }

    constructor(name: String) : this(name, 0) {

    }

    //Secondary constructors with different parameters
    constructor(name: String, age: Int) : super(name, age) {
        Log.e("TAG,", "Subclass constructor executed $name===$age")
    }
}

😜 [interface]

This is also similar to Java. There is no difference in the use of [interface] definition

The keywords of the modifier class are

  • Abstract / / indicates that this class is abstract
  • final / / indicates that this class is non inheritable. The default attribute is
  • enum / / indicates that this class is an enumeration class
  • open / / indicates that the class is inheritable. The class is final by default
  • Annotation / / indicates that this class is an annotation class

Modifiers for access rights are:

  • private / / access rights - visible only in the same file
  • protected / / access rights - visible in the same file or subclass
  • public / / access permission - visible to all calls
  • internal / / access permission - visible in the same module

After learning and experimental verification, Xiaokong decided to use Java entity classes. Anyway, they have interoperability.

😜 [abstract class / nested class / inner class]

Xiaokong will take you directly to see with examples

abstract class EntityThree {
    abstract fun methonOne()
}

//Nested class instance
class One {                  // This is an external class
    private val age: Int = 1
    class Two {             // This is a class inside a class, called a nested class
        fun hello() {

        }

        fun hi() = 3
    }
}

//The inner class uses the keyword inner
class Three {
    inner class Four { //This Four class is an inner class
        fun hello() {

        }
        fun hi() = 3
    }
}
//This is a reference example
var one = Three().Four().hello()

😜 [data type]

A data class is an entity class in Java

In Kotlin, the data class is decorated with the keyword [data]. It is declared in front of the class class and contains only data. In fact, it is the same thing as the entity class generated by Jason in Java, with several built-in function methods

equals() compare function

toString() format, such as "User(name=John, age=42)"

componentN() functions correspond to attributes, arranged in declaration order

copy() assignment function

When developing in Java, we will use the GsonFormat plug-in to quickly generate the Json data of the interface into an entity.
Now Kotlin has a similar plug-in called [Jason to Kotlin class].
Go to [file setting plugins] to search for installation.
Use: use the shortcut key [Alt+K] (if it does not conflict with other shortcut keys) or open the [Generate...] function box, which contains [Kotlin data classes from JSON]

Being good at using plug-ins can quickly help us improve work efficiency, improve irreplaceable at work, and then realize salary increase.

Let's talk about sealing classes here. For the time being, I didn't expect a more common application environment. The original words of the rookie tutorial are as follows:

A sealed class is used to represent a restricted class inheritance structure: when a value has a limited number of types and cannot have any other types. In a sense, they are extensions of enumeration classes: the value collection of enumeration types is also limited, but there is only one instance of each enumeration constant, while a subclass of a sealed class can have multiple instances of states.

Declare a sealed class and use sealed to decorate the class. A sealed class can have subclasses, but all subclasses must be embedded in the sealed class.

sealed cannot modify interface and abstract class (warning will be reported, but no compilation error will occur)

😜 [generic]

Generics is also one of the functions commonly used in our development process. Like Java, Kotlin also uses T to represent generics, which makes the code more robust and solves the unknown steps of type conversion.

class Person<T>(t: T) {
    var value = t
}

Use examples are as follows:

//Usage example
var age = Person<Int>(20)
var name = Person<String>("Runoob")
Log.e("TAG,", "Output: $age")
Log.e("TAG,", "Output: $name")

There is no obvious difference between the use of generic constraints and Java

fun <T : Comparable<T>> myHeight(list: List<T>) {
    // ......
}
myHeight(listOf(1,2,3,4))

The above example is correct because Int is a subtype of Comparable

👉 other

📢 Author: Xiaokong and Xiaokong in Xiaozhi
📢 Reprint instructions - be sure to indicate the source: https://zhima.blog.csdn.net/
📢 Welcome to praise 👍 Collection 🌟 Leaving a message. 📝

Topics: Programming Android kotlin