Classes and objects in kotlin language

Time:2021-7-27

1. Class

A class represents an abstraction of a concrete object. For example, if a person represents a class, then I am a concrete object myself; In the class, attributes describe the object state of the class, and functions describe the object function of the class; Like Java, kotlin uses the class keyword to modify the name of the corresponding class; The following defines a class with kotlin Code:

PS: the code is written in Android studio

/**
 *Define a class called person
 */
class Person {
 /**
 *Define a string type attribute name
 */
 var name: String? = null
 /**
 *Define an int type attribute
 */
 var age: Int = 0
 constructor(name: String,age: Int) {
 this.name = name
 this.age = age
 }
 /**
 *Define a function called eat
 */
 fun eat() {
 Var s: String = "my name is" + name + ", I'm" + age + "years old this year, and I'm eating now"
 println(s)
 }
}

**2. Object
**

An object is the materialization or instantiation of a class. Creating an object does not need the new keyword, but only needs the “class name ()” to successfully instantiate a class.

3、   Static properties and dynamic behavior

The basic data type or complex data type declared in a class is called static attribute. The static attribute here does not mean the data type of static type, but it is our convention to say that the attribute is static. Don’t confuse it; In the person class defined above, name and age are static attributes, which only need to be called by the object; The function defined in a class is to define the dynamic behavior. Take the person class for example, the eat () function is the dynamic behavior, and it also needs to be called by the object when it needs to be used.

4. Encapsulation

Encapsulation is actually hiding the internal implementation details. For example, if a class defines a function in private, it encapsulates the class. It cannot be accessed externally through the object, but only through the object itself, that is, the function defined in the object’s own private is accessed through the object function; Here is an example:

(1) Define a printer class.

class Printer {
 /**
 *Here, the print speed is encapsulated with the printspeed function and declared with private;
 *It cannot be changed externally
 */
 private fun printSpeed(num: Int) {
 Println ("1 minute print" + num + "sheet of paper")
 }
 fun printPaper() {
 /**
 *Here, the object function can call the private function of the object itself,
 *The private method of an external object cannot be called
 */
 printSpeed(10)
 }
}

(2) The printpaper method of printer class object is called externally, and the printspeed method cannot be called directly.

 var printer: Printer = Printer()
 printer.printPaper()

5. Inherit

An object can use the non private properties and non private methods of another object, which is called inheritance. For example, students can also inherit the name, age properties and eat methods of human person. One class inherits another class, which means that the open keyword should be added to the definition of the inherited class, Because in the kotlin language, the class is the default final type (if it is not an abstract class or interface); Here is an example:

(1) Define a student class and inherit the person class. Add an open keyword before the person class.

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

(2) Directly call the eat method that inherits the parent class.

Var student: student = student ("sophomore", 21)
 student.eat()

6、 rewrite

When a class inherits from another class, a subclass can override the non private methods of the parent class; Rewriting can be understood as that when the parent has its own dream, the child can inherit the parent’s dream and also have its own small dream; When a subclass rewrites a function, the override keyword should be added. When a subclass object calls a function with the same function name as the parent and subclass, it calls the function rewritten by the subclass object, not the function of the parent object; Add the open keyword before the function of the inherited class, because in kotlin language, the function is the default final type and cannot be overridden (if it is not an abstract function); Here is an example:

(1) Add a dream function based on the person class.

open fun dream() {
 Var s: String = "my name is" + name + ", and I am" + age + "years old this year. My dream is to make life better."
 println(s)
 }

(2) Rewrite the dream function based on the student class.

override fun dream() {
 Var s: String = "my name is" + name + ", and I am" + age + "years old. I dream of doing business."
 println(s)
 }

(3) Call the dream function

Var student: student = student ("sophomore", 21)
 /**
 *What is called here is the student's own, not the person's
 */
 student.dream()

7. Abstract class

A class containing the abstract keyword is called an abstract class. An abstract class can have abstract functions or none at all; If there are abstract functions, the class that inherits the abstract class must implement all the abstract functions of the abstract class; Abstract classes do not need to add the open keyword because they are inheritable by default; Here is an example:

(1) Create a new abstract class father.

abstract class Father {
 abstract fun study()
}

(2) Create a new son class, inherit the father class and implement the study function.

class Son: Father() {
 override fun study() {
 Var s: String = "I'm son, I want to learn"
 println(s)
 }
}

(3) Call the study function.

 var son: Son = Son()
 son.study()

8、 Interface

Interface refers to an abstraction that an entity provides itself to the outside world to separate external communication methods from internal operations; In kotlin language, an interface is a special abstract class. It can declare functions or not. If there are functions declared, all its functions are abstract functions; The interface keyword is used to define the interface, instead of the class keyword, and there is no need to add the open keyword, because it is inheritable by default for external use; The function declared in the interface does not need to write the keywords open and abstract, because it is an abstract function and is implemented by subclasses; When a subclass implements an interface, parentheses cannot be added after the interface; Here is an example:

(1) Define an interface myinterface.

interface MyInterface {
 fun callback()
}

(2) Define an implementation class myinterfaceimplement.

class MyInterfaceImplement: MyInterface {
 override fun callback() {
 Var s: String = "I am a myinterfaceimplement class object, and I implement the callback function of myinterface interface"
 println(s)
 }
}

(3) Call the interface method.

 var myInterfaceImplement: MyInterfaceImplement = MyInterfaceImplement()
 myInterfaceImplement.callback()

9. Polymorphism

The same function and different manifestations are called polymorphism; What do you mean? For example, if an abstract class has an abstract function and multiple subclasses inherit the abstract class, the abstract function of the abstract class is the same function, and the functions of the abstract class implemented by multiple subclasses with different codes are different manifestations; Here is an example:

(1) On the basis of myinterface, create a new myinterfaceimplemenment2 class and implement myinterface interface.

class MyInterfaceImplement2: MyInterface {
 override fun callback() {
 Var s: String = "I am a myinterfaceimplemenment2 class object. I implement the callback function of myinterface interface"
 println(s)
 }
}

(2) Instantiate multiple myinterface interfaces and call their functions.

/**
 *Upward transformation
 */
 var myInterface: MyInterface = MyInterfaceImplement()
 var myInterface2: MyInterface = MyInterfaceImplement2()
 var list: List<MyInterface> = listOf(myInterface,myInterface2)
 for (myInterface: MyInterface in list) {
 /**
 *Although this is the same interface function, it is the specific code of myinterfaceimplementation and myinterfaceimplemenment2 functions
 */
 myInterface.callback()
 }

10. Principal and agent

Entrustment is to entrust things to others, and agency is an act that has a direct legal effect on the principal in the name of others and with permission; For example, a singer signs a contract, but he doesn’t sign directly. He still asks an assistant to sign a contract. This is a typical principal-agent model; Here is an example:

(1) Define an interface company.

interface Company {
 fun sign()
}

(2) Define a singer assistant class, singer assistant, and implement the company interface.

class SingerAssistant: Company {
 override fun sign() {
 Var s: String = "I'm the singer's assistant. I sign on behalf of the singer"
 println(s)
 }
}

(3) Define a singer class to implement the company interface, but not the function. Instead, use the singer assistant agent to implement the function.

class Singer: Company by SingerAssistant() {
}

(4) Call the function.

var company: Company = Singer()
 /**
 *Singer was originally used to implement the function, but it uses a delegate,
 *Therefore, the singer assistant agent implements the function
 */
 company.sign()

11. Singleton mode

In a process, there is only one class object, which is called singleton pattern; In the kotlin language, to create a singleton pattern, you only need to add the object keyword to a class and remove the calss keyword, so that the JVM can be instantiated, and only one instance will appear; Here is an example:

(1) Define a singleton pattern class.

object Singleton {
 fun action() {
 Var s: String = "I am a singleton class object, and it is not allowed to instantiate more than one object"
 println(s)
 }
}

(2) Call the class object method of the singleton pattern.

/**
 *Because a class that is a singleton pattern is defined here,
 *Therefore, when calling, you only need to call the class name
 */
 Singleton.action()
 /**
 *An error will be reported here because it is a singleton mode, and you can't instantiate another class object
 */
 var singleton: Singleton = Singleton()

12. Seal class

Seal class, also known as seal class, is used to represent the restricted class inheritance structure: when a value has a limited number of types and cannot have any other types; It can also be understood as a restricted subclass, which is an extension of enumeration type. The difference is that enumeration type is a limited number of data, while seal type is a limited subclass type; Use the sealed keyword to modify the class. The seal class can have subclasses, but all subclasses must be embedded in the seal class; Here is an example:

(1) Define a seal class snake.

sealed class Snake {
 class WaterSnake(): Snake()
 class GrassSnake(): Snake()
 fun sayName(name: String) {
 println(name)
 }
}

(2) Call the functions of all subclasses of the seal class.

 var snake: Snake = Snake.GrassSnake()
 var snake2: Snake = Snake.WaterSnake()
 var list:List<Snake> = listOf(snake,snake2)
 for (snakes: Snake in list) {
 snakes.sayName()
 }

This article ends here. Due to the limited technical level, there will inevitably be errors in the article. You are welcome to criticize and correct. In addition, the demo address is attached:https://github.com/Yubao1/Kot…

Recommended Today

VBS obtains the operating system and its version number

VBS obtains the operating system and its version number ? 1 2 3 4 5 6 7 8 9 10 11 12 ‘************************************** ‘*by r05e ‘* operating system and its version number ‘************************************** strComputer = “.” Set objWMIService = GetObject(“winmgmts:” _  & “{impersonationLevel=impersonate}!\\” & strComputer & “\root\cimv2”) Set colOperatingSystems = objWMIService.ExecQuery _  (“Select * from […]