The road to learning Kotlin (4): classes, constructors, objects

foreword

There is a big difference between kotlin classes and Java classes, and it is also a focus of kotlin learning. The following is the introduction of kotlin classes and related knowledge points.

1. Class & Member Variables & Methods

1.1 Access Modifiers

Friends who are familiar with Java should know that Java has these access modifiers: private, default (default), protected, public.
The following is a table of Java access modifiers:

access modifier same class same package Subclass anywhere
private yes no no no
default (default) yes yes no no
protected yes yes yes no
public yes yes yes yes
(Yes: accessible, No: not accessible)

So what about kotlin access modifiers?
In kotlin, change default (default) to public, and add internal, and the others are the same as Java.

The following is the kotlin access modifier table:

access modifier same class same package Subclass the same module anywhere
private yes no no no no
protected yes yes yes no no
internal yes yes yes yes no
public (default) yes yes yes yes yes

For the modifier of class, it needs to be emphasized:

  1. internal, the scope of this modifier is a module. The so-called module can be considered as a component, a third-party support package, and variables or classes modified by internal cannot be used by other modules.
  2. The class class is by default (without any modifiers) public final, which means that by default, 1. The class is public and can be accessed by other classes; 2. The class cannot be inherited .

1.2 Classes and Objects

The following is the simplest class

// 定义了一个Person类
// kotlin默认访问权限修饰符就是public
class Person {
    
    
}

fun main(){
    
    
    val person = Person() // 创建一个Person对象
    // val person0:Person = Person() // 带类型的声明
    println(person) // person对象
}

The creation of objects in kotlin is much simpler than that in Java, and even the new keyword does not need to be written.

1.3 Member variables and member methods

class Person {
    
    
	// 成员变量
    var name:String = "Jack"
    var age:Int = 23
    
    // 只读
    val id = 1001
	
	// 成员函数
    fun eat(food:String){
    
    
        println("eat $food")
    }
}

fun main(){
    
    
    val person = Person()
//  var person = Person() // 创建一个只读的Person对象
    println(person.name)
    println(person.age)
    println(person.id)
    person.eat("rice");
}

output:

Jack
23
1001
eat rice

In the above code example, both member variables and member methods are public, so they can be called directly in the main function. Readers can also try to change to private to modify.

2. Constructor

There is still a big gap between kotlin's constructor and Java's constructor. Kotlin's constructor is mainly divided into primary constructor and secondary constructor, which will be introduced one by one below.

2.1 Primary constructor

Kotlin, like Java, has a default constructor that takes no arguments. If parameters are specified, the general writing is as follows:

The general way of writing a primary constructor with parameters is as follows:

// 自动创建同名的成员变量name和age,同时默认是public属性的
class Person constructor(var name:String, var age:Int){
    
    
}

fun main(){
    
    
    val person = Person("Jack", 23)
    println("name is ${
      
      person.name} age is ${
      
      person.age}")
}

output:

name is Jack age is 23

There are a few things to note about the above code:

  1. constructor(var name:String, var age:Int)It is the main constructor of this class. constructorKeywords can be omitted.
  2. Among them, var name:String, var age:Inta member variable with the same name will be automatically created in the class ( valthe modified one is the same), and the initialized value is the parameter value of the constructor.
  3. For the parameters of the primary constructor var name:String, var age:Int. If not added var, a member variable with the same name will not be created, but only represent the parameters of the function.

Anyone who has written Java knows that Java classes can be initialized in the function body of the constructor:

public class Person {
    
    
    public Person() {
    
    
    	// 构造函数的函数体,这个可以省略
    }
}

So does Kotlin have similar functionality? The answer is yes! This requires an introduction to the usage of Kotlin init{}.

class Person constructor(name:String, age:Int){
    
    
	// 成员变量
    var mName:String = ""
    var mAge:Int = -1;
    // init代码块
    init {
    
    
    	// 类似Java构造函数体
        mName = name
        mAge = age
        // 其他的初始化过程
    }
}

fun main(){
    
    
    val person = Person("Jack", 23)
    println("name is ${
      
      person.mName} age is ${
      
      person.mAge}")
}

The above example is the correct init{}use, you can init{}implement the initialization function of the class in it, just like using the function body of the Java constructor.

As mentioned earlier, in order to simplify the main constructor code, Kotlin constructorcan be omitted as a keyword:

class Person(var name:String, var age:Int){
    
    
}

Doing so can make the code more concise. Of course, the keywords of the main constructor constructorare not useless. When you need to add access rights to the constructor, you need to add it constructor.

// 直接将构造函数修饰为private
class Person private constructor(var name:String, var age:Int){
    
    
}

fun main(){
    
    
	// 由于设置构造函数为privae,无法创建对象。
    val person = Person("Jack", 23) // 报错
    println("name is ${
      
      person.name} age is ${
      
      person.age}")
}

Since the main constructor can add access modifiers, the member variables name and age can also be added:

// 相当于成员变量name和age设置为private
class Person constructor(private var name:String, private var age:Int){
    
    
}

fun main(){
    
    
    val person = Person("Jack", 23)
    // 由于成员变量name和age设置为private,所以这里报错
    println("name is ${
      
      person.name} age is ${
      
      person.age}")
}

The above is how to use the main constructor. Through the above example, you can conclude a sentence. In Kotlin, the main constructor is the entry point of the class .

2.2 Secondary constructors

For Java, we know that the constructor can be overloaded, and the same is true for kotlin. There is an overload of the constructor, which is the secondary constructor.

class Person (var name:String, var age:Int){
    
    

    // 次构造函数
    constructor(name: String):this(name, 22)

    // 次构造函数
    constructor(age: Int):this("Jack", age)
    
// private constructor(age: Int):this("Jack", age)
}

fun main(){
    
    
    val person0 = Person("Jack")
    println("name is ${
      
      person0.name} age is ${
      
      person0.age}")

    val person1 = Person(23)
    println("name is ${
      
      person1.name} age is ${
      
      person1.age}")
}

Like the primary constructor, the secondary constructor can also be preceded by an access modifier.
There is a very important rule for the secondary constructor, that is, the secondary constructor must directly or indirectly call the primary constructor.
The following code is a wrong example:

class Person (var name:String, var age:Int){
    
    

    // 次构造函数
    constructor(name: String):this(name, 22)

    // 次构造函数
    constructor(age: Int) // 报错
}

This error is thrown if the secondary constructor does not call the primary constructorPrimary constructor call expected

Three. this keyword

thisKeywords In addition to the above used to point to the primary constructor, thiskeywords also represent objects of the current class.

/**
 * 这里的this都代表当前类的对象
 */
class Person (name:String, age:Int){
    
    
    var name:String = "name"
    var age:Int = 22
    init {
    
    
        this.name = name
        this.age = age
    }

    fun selfIntroduce(){
    
    
    	// 这里也可以省略this
        println("I am ${
      
      this.name}, ${
      
      this.age} years old")
    }
}

fun main(){
    
    
    val person = Person("Jack", 23)
    person.selfIntroduce()
}

output:

I am Jack, 23 years old

Another usage of this is with a qualifier. this@xxxThis usage is mainly used for anonymous classes and inner classes, and will be supplemented later when introducing anonymous classes and inner classes.

Finish

The above is about the simple use and introduction of kotlin classes, constructors, and objects. Welcome to correct mistakes and share.

Guess you like

Origin blog.csdn.net/RQ997832/article/details/122890951