What is a class?

A class is an abstract concept, a generalization of things with certain characteristics, and does not specifically refer to any specific thing. Writing:

class <The name of the class> {< member >}Copy the code

Number(Int, Float, Byte) and String (String) are also classes

class Girl constructor(var nature: String,var appearance: String,var sound: String){
    // Construct the body of the method
    init {
        println("Girl's personality:$natureThat looks like:$appearanceVoice:$sound")}}Copy the code
  • constructorIs the constructor keyword, which can be omitted if there is only one constructor.
  • initIs the body of the constructor method that is executed when an object is created from the class.
fun main(args: Array<String>) {
    val girl: Girl = Girl("Tender"."Sweet"."Moving") // Girl's personality: gentle, looks: sweet, voice: touching
}
Copy the code

Class constructor

There are two types of constructors:

  • Primary constructor: The constructor immediately after the class name, with parameters that can be usedvarThe statement,initIs the method body of the main constructor.
  • Secondary constructor: a constructor declared in a class code block. The arguments are not availablevarStatement, andinitNo direct relationship.
class Girl constructor(var nature: String, var appearance: String, var sound: String) {

    // The method body of the main constructor
    init {
        println("Girl's personality:$natureThat looks like:$appearanceVoice:$sound")}// Secondary constructor, cannot declare variables using var
    constructor(nature: String, appearance: String) : this(nature, appearance, sound = "Unknown") {
        println("Secondary constructor")}}fun main(args: Array<String>) {
    val girl: Girl = Girl("Tender"."Sweet")
    // Output 2 sentences:
    // Girl's personality: gentle, looks: sweet, voice: unknown
    // The secondary constructor is called
}
Copy the code

As mentioned above, the secondary constructor is not directly related to init, but the secondary constructor will pass :this(…) Invoke the primary constructor, triggering the init method body execution. In addition, the output confirms that the secondary constructor method body executes later than the init method body.

Personal advice: write init first and then the secondary constructor, it looks more comfortable.

Constructor elisionconstructorThe keyword

The constructor keyword can be omitted when there is no secondary constructor and only one primary constructor:

class Girl(var nature: String, var appearance: String, var sound: String) {
    ...
}
Copy the code

In the main constructorvarparameter

The primary constructor can only use var for its arguments, but the secondary constructor cannot.

// Note that only nature uses the var declaration
class Girl constructor(var nature: String, appearance: String, sound: String) {

    init {
        println("Girl's personality:$natureThat looks like:$appearanceVoice:$sound")}fun test(a) {
        println(nature) / / compile OKprintln(appearance)// Failed to compileprintln(sound)// Failed to compile}}Copy the code

The init method body has access to all of the main constructor arguments, whereas the test() method has access to only the constructor arguments declared by var.

  • In the main constructor, usevarDeclared parameters, which become member variables, can be called in various methods of the class.
  • Instead of usingvarDeclare parameters, only temporary variables, only ininitUsed in the body of a method.

Class inheritance

If a subclass inherits its parent class, it can obtain the abilities of the parent class. Kotlin uses: Connect the parent class to form an inheritance relationship.

open class Human(nature: String, appearance: String, sound: String) {
    init {
        println("${this.javaClass.simpleName}Character:$natureThat looks like:$appearanceVoice:$sound")}}class Girl(nature: String, appearance: String, sound: String) : Human(nature, appearance, sound)
class Boy(nature: String, appearance: String, sound: String) : Human(nature, appearance, sound)
Copy the code

From a Java developer’s point of view, classes in Kotlin are final by default, and using classes decorated with open removes the final keyword.

Subclass constructor

In the above example, neither Girl nor Boy has a var declaration for their main constructor arguments, and can’t actually use var declarations either. Here’s an example:

// error: 'Nature' hides member of supertype 'Human' and needs 'override'
class Boy(var nature: String, appearance: String, sound: String) : Human(nature, appearance, sound)
Copy the code

Human (‘ Human ‘, ‘nature’, ‘Human’, ‘nature’, ‘Human’);

// error: 'nature' in 'Human' is final and cannot be overridden
class Boy(override var nature: String, appearance: String, sound: String) : Human(nature, appearance, sound)
Copy the code

It is not enough to simply append the override keyword to Nature, because the constructor parameter defaults to a final, immutable variable. To remove this restriction, append the open keyword to the nature parameter in the parent Human main constructor.

open class Human(open var nature: String, var appearance: String, var sound: String) {
    ...
}
class Boy(override var nature: String, appearance: String, sound: String) : Human(nature, appearance, sound)
Copy the code

Well, finally put the main constructor parameter nature of subclasses Boy, the var statement, so what? The answer is not much.

We can use nature in a member method of Boy even if nature does not have a var declaration. We can use nature in a member method of Boy even if nature does not have a var declaration declaration. It is a member variable of the parent class Human (similar to protected Final String Nature in Java) and can be recognized and called by the child class Boy. So, after all, when do we need to use var to declare a subclass’s main constructor argument with the same name as the parent constructor argument?

open class Human(nature: String, var appearance: String, var sound: String) {
    ...
}

class Boy(var nature: String, appearance: String, sound: String) : Human(nature, appearance, sound)
Copy the code

When the main constructor parameter of the parent class is not declared with var, and the subclass needs to use the parameter in the member method, we can append the parameter with var in the constructor of the subclass to make it a member variable of the subclass. Otherwise, subclass main constructor arguments are used no differently than normal main constructor arguments.

Any class

In Kotlin, Any is the ancestor of all classes, the equivalent of Object in Java.

/** * The root of the Kotlin class hierarchy. Every Kotlin class has [Any] as a superclass. */
public open class Any {... }Copy the code

Package (Package)

  • Packages are namespaces
  • The package declaration must be on the first line of uncommented code
  • The full name of the class isPackage name + class name, such as: com. Area. Through. The Human

For example, declare a Human class under the com.area.guangzhou package:

packagecom.area.guangzhou// First line of code: package declaration
/** ** from Guangzhou */
class Human {}Copy the code

A Human class can be declared in com.area.shantou, for example: com.area.shantou

package com.area.shantou
/** ** ** */
class Human {}Copy the code

Since the class name is the same, we need to use the full name of the class in order to distinguish between two Human’s in the same file:

fun main(args: Array<String>) {
    val gzHuman = com.area.guangzhou.Human()
    val stHuman = com.area.shantou.Human()
}
Copy the code

We can alias the package using the as keyword:

import com.area.guangzhou.Human asSelf-sufficient peopleimport com.area.shantou.Human asGlue has onefun main(args: Array<String>) {
    valGzHuman = self-sufficient ()valStHuman = stHuman ()}Copy the code

Note: the code here is for demonstration only, in the actual development, in order to avoid unnecessary trouble, it is best not to use Chinese for coding.