SoFunction
Updated on 2025-03-11

Kotlin object-oriented knowledge points explanation

Classes and Objects

Create a Person class

open class Person {
    /**
      * Name
      */
    var name = ""
    /**
      * age
      */
    var age = 0
    /**
      * How to eat
      */
    fun eat() {
        print(name + " is eating. He is" + age +"years old.")
    }
}

Create a Person object in the main function, assign characters, and call methods in the class

fun main() {
    val p = Person();
     = "Zhang San"
     = 10
    ()
}

Note that creating objects in Kotlin does not require new keywords

Inheritance and constructor functions

  • Inheritance is a major feature of object-oriented
  • What is different from java in Kotlin is that in Koitlin any non-abstract class cannot be inherited by default, which is equivalent to adding the final keyword to a class in java
  • Because a book called Effective Java clearly mentions that if a class is not designed specifically for inheritance, then it should add a final statement to prohibit it from being inherited. This belongs to the programming specification.
  • There is no difference between abstract classes and java in Kotlin
  • If you want a class to be inherited in Kotlin, you just need to prefix the open keyword in this class.
  • If a class wants to inherit a class, the extends keyword is used in java, and the keyword is used in Kotlin:. Moreover, the parent class not only needs to write the class name but also needs to include a pair of brackets.
class Student : Person() {
    var sno = ""
    var grade = 0
}

The main constructor of a class in Kotlin

Each class will have a main constructor without parameters by default, but we can also display it assign parameters. The characteristic of the main constructor is that there is no function body, and it can be directly defined after the class name.

class Student(val sno: String, val grade: Int) {
}

The above line of code means that the main constructor of Student has two parameters, namely sno and grade.

There is no function body in the main constructor, so it is OK for us to write some code logic in the main constructor. We can implement it through the init structure

class Student(val sno: String, val grade: Int) {
    init {
        println("sno is " + sno)
        println("grade is" + grade)
    }
}

Through the init structure, some code logic can be executed for the main constructor

So when a subclass inherits the parent class, why does a pair of brackets follow the parent class name? The reason is that when a subclass inherits the parent class, the subclass constructor must call the parent class constructor, so the main constructor of the subclass calls the parent class constructor, which is specified by this().

class Student : Person() {
    var sno = ""
    var grade = 0
}

Here, a pair of empty brackets after Person class indicates that the main constructor of the Student class will call the Person class's parameterless constructor when initialized.

Secondary constructor: In Kotlin, each class can only have one main constructor, but there can be multiple secondary constructors, and the secondary constructor can also instantiate a class. The difference is that the main constructor has no function body, and the secondary constructor has a function body

Kotlin stipulates that if both the main constructor and the secondary constructor exist in a class, all the secondary constructors must call the main constructor (including indirect calls)

The subconstructor function is declared through the constructor keyword

class Student(val sno: String, val grade: Int, name: String, age: Int) : 
Person(name, age) {
    //Second constructor 1: Directly call the main constructor of this class. This secondary constructor has two parameters, nanom and age. When calling the main constructor of this class, it directly instantiates the two parameters sno and grade in the main constructor, and then passes its name and age to the called main constructor.    constructor(name: String, age: Int) : this("", 0, name, age){
    }
    //Second constructor 2: No parameters are received, and then the main constructor of this class is not called directly, but the secondary constructor 1 is called, which is equivalent to indirectly calling the main constructor of this class.    constructor() : this("Zhang San", 18)
}

After the Student class is written in the above method, we can instantiate it using the main constructor or this constructor. Then there are three ways to instantiate the Student class.

//Instantiate the Student class using the main constructorval student1 = Student("123", 1, "Zhang San", 18)
//Instantiate Student using subconstructor 1val student2 = Student("Zhang San", 18)
//Instantiate Student using subconstructor 2val student3 = Student()

There is also a special case where the class only contains a secondary constructor and does not have a primary constructor. Although this case is rare, it is allowed in Kotlin. When a class does not display the primary constructor but defines the secondary constructor, it does not have the primary constructor.

class Student : Preson {
    constructor(name: String, age: Int) : super(name, age) {
    }
}

In the above code, first, the main constructor is defined according to the undisplayed one, and the secondary constructor is defined. Therefore, the Student class does not have a main constructor. Because there is no main constructor, the main constructor of the subclass calls the main constructor of the parent class. Therefore, there is no () added after the Person class.

In addition, since there is no main constructor, this constructor can only directly call the constructor of the parent class. Therefore, when the secondary constructor calls the method, the keyword this keyword is replaced by the super keyword.

interface

The interfaces in Kotlin are almost exactly the same as those in java. Interfaces are an important part of polymorphic programming. Java is a single inheritance language, but multiple interfaces can be implemented. The same is true in Kotlin.

Define a Study interface

interface Study {
    fun  readBooks()
    fun doHomeWork()
}

Student implements Study interface

class Student : Person(), Study{
    var sno = ""
    var grade = 0
    override fun readBooks() {
        println("read")
    }
    override fun doHomeWork() {
        println("Do homework")
    }
}

In Java, the keyword used for inheritance is extends, the implementation uses the impls keyword, and in Kotlin, the keyword used is: , if inheritance is done and implementation is implemented, use, and separate

In the above code, Student implements the Study interface, so he must implement two methods in Study. In Kotlin, use the override keyword to rewrite the parent class or implement the methods in the interface.

Characteristics of polymorphic programming

fun main() {
    val student = Student()
    doStudy(student)
}
fun doStudy(study: Study) {
    ()
    ()
}

Because Student implements the Study interface, in the doStudy method, the parameter that needs to be passed is Study type, so you can also pass an instance of Student

Another point is that in Kotlin, you can implement abstract methods in interfaces by default.

interface Study {
    fun  readBooks()
    //The method can be implemented by default in Kotlin's interface    fun doHomeWork() {
        println("do homework")
    }
}

If a function in the interface has a function body, the content in this function is its default implementation. Now when a class implements the Study interface, it will only force the implementation of the readBooks method, and the doHomeWork method can be freely selected for implementation, and it will not automatically use the default implementation logic first.

Access modifier

There are four types of access control characters in Java: public, private, protected, and default (write nothing)

There are also four types of access control characters in Kotlin: public, private, protected and internal. When you need to use the modifier, just add it in front of the fun keyword.

The private modifier functions in java and Kotlin, both representing visible inside the current class

Although the function of the public modifier is consistent, it means that it is visible to all classes. However, in Java, default is the default item, but in Kotlin, public is the default item

protected keyword is visible in java, the class and the subclass of the class and the same package, but in Kotlin, the value is visible to the class and subclass.

Kotlin abandons the default permission in java (visible under the same package path) but introduces a new permission internal

Internal means that the class in the same module is visible. For example, we develop a module for others to use, but some functions only allow calls inside the module and do not want to be exposed to the outside. Then these functions can be modified with the internal keyword

Data classes and single cases

Data classes usually need to rewrite equals, hashCode, and toString methods, where equals method is used to determine whether two data are equal. hashCode method is a supporting method of equals method. The toString method is used to print a clearer log, otherwise the data is printed out as a string of addresses.

These methods must be implemented one by one in java

But in Kotlin, you only need to use the date keyword to solve it

data class Cellphone(val brand: String, val price: Int)

In the above line of code, I defined a data class. When a date keyword is placed in front of class, it means that I hope this class is a data class. Kotlin will rewrite the equals, hashCode, and toString methods based on the parameters in the main constructor. In addition, when there is no code in a class, the {} of the class can be omitted

Next is the singleton class. Singleton pattern is a basic design pattern. When we are developing, we hope that a certain class can only have one instance globally, so that the singleton pattern can be used. There are many ways to write singleton pattern in Java language. Although it is simple, there are simpler methods in Kotlin.

Creating a singleton class in Kotlin is very simple. You just need to change the class keyword to the object keyword. When creating the class, just select object directly and do not select class.

object Singleton {
}

Now Singleton is already a singleton class. We can directly write the required functions in this class, such as adding a singletonTest method

object Singleton {
    fun singletonTest() {
        println("this is a singleTon.")
    }
}

It can be seen that in Kotlin we do not need to privatize the constructor, nor do we need to provide static methods such as getInstance(). We only need to modify the class keyword and become the object keyword.

The above code can be used directly to use () when calling it. This writing looks like a static method call, but in fact, Kotlin automatically creates an instance of the Singleton class behind it.

This is the end of this article about Kotlin object-oriented knowledge points. For more related Kotlin object-oriented content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!