Talking about Kotlin (III): Class, talking about kotlin

Source: Internet
Author: User

Talking about Kotlin (III): Class, talking about kotlin

Kotlin (1): Introduction and configuration in Android Studio

Kotlin (2): basic types, basic syntax, and code style

Talking about Kotlin (3): Class

 

Preface:

I have learned the first two articles and have a basic understanding of Kotlin. later articles will introduce the practical use of Kotlin.

This topic describes how to use classes in Kotlin.

 

I. Forms

First, let's look at the form of defining classes in Java and define three attributes. Each attribute corresponds to a get and set method, and there is a toString () method.

/** @ Author xqx * @ emil djlxqx@163.com * create at least /5/18 * description: Self-written class, person, including name, age, gender */public class XPatient {private String name; // name private int age; // age private int sex; // gender 1, male 2, female public String getName () {return name;} public void setName (String name) {this. name = name;} public int getAge () {return age;} public void setAge (int age) {this. age = age;} public int getSex () {return sex;} public void setSex (int sex) {this. sex = sex ;}@ Override public String toString () {return "XPatient {" + "name = '" + name +' \ ''+ ", age = "+ age +", sex = "+ sex + '}';}}

  

Next we will look at the corresponding Kotlin representation of this class:

Perform the following operations to convert the. java file corresponding to this class to the corresponding. kt file.

  

  

After the conversion, let's look at the converted code:

Let's take a look at the changes:

1. Less code

2. No get/set methods are available.

3. There is only one rewritten toString () method.

4. All class attributes have a default initial value.

/** @ Author xqx * @ emil djlxqx@163.com * create at least /5/18 * description: Self-written class, person, including name, age, gender */class XPatient {var name: String? = Null // name var age: Int = 0 // age var sex: Int = 0 // gender 1, male 2, female override fun toString (): string {return "XPatient {" + "name = '" + name +' \ ''+", age = "+ age + ", sex = "+ sex + '}'}}

 

Ii. constructor of definition classes

First, let's look at the construction of Java classes.

Features of the constructor defined in Java:

1. The method name must be consistent with the class name

2. A parameter can be a combination of any attribute values or not written.

3. There can be multiple constructor Methods

// Non-parameter constructor public JPatient () {}// the constructor required for all three attribute values of the class public JPatient (String name, int age, int sex) {this. name = name; this. age = age; this. sex = sex ;}

  

Looking at the Kotlin class, here is a knowledge point: The Kotlin class can have a primary constructor and a maximum of two constructor methods.

① Writing of the main constructor method:

Directly write it in the Class header, similar to adding a parameter in the form of defining a method.

You need to add the init {} code block to process the initialization operation of parameters sent from the main constructor.

Class XPatient (name: String? , Age: Int, sex: Int) {// form of the main constructor. Add the class name (attribute name: attribute type...) var name: String? = Null // name var age: Int = 0 // age var sex: Int = 0 // gender 1, male 2, female/* initialize the main constructor, custom */init {this. name = name; this. age = age + 1; this. sex = sex-1 ;}....}

    

 ② Second-level constructor:

To implement a class similar to Java, a class has multiple constructor methods.

The second-level constructor is finally delegated to the primary constructor. There can be 0 or more intermediate second-level constructor methods in the middle.

Personally, if a class involves multiple constructor methods, set the primary constructor as non-parametric.

As follows: When you create an object XPatient ("Alice", 18);, the second-level constructor (name: String ?, Age: Int): this (name ){}

Constructor (name: String ?) : This (){}

The second-level constructor of a parameter is the final principal Constructor (called ).

  The following is an example:

Class XPatient (){
Var name: String? = Null // name
Var age: Int = 0 // age
Var sex: Int = 0 // gender 1, male 2, female


/* Initialize the main constructor */
Init {
Log. I ("xqxinfo", "the primary constructor without parameters is called ");
}

/* Input (name )*/
Constructor (name: String ?) : This (){
This. name = "Alice ";
Log. I ("xqxinfo", "the second-level constructor of a parameter is called ");

}
/* Input (name, age )*/
Constructor (name: String ?, Age: Int): this (name ){
This. age = age + 1;
Log. I ("xqxinfo", "Two Parameter level constructor called ");
}

Override fun toString (): String {
Return "XPatient {" +
"Name = '" + name +' \ ''+
", Age =" + age +
", Sex =" + sex +
'}'
}
}

Test:

Val patient = XPatient ("Alice", 18)
Log. I ("xqxinfo", "attribute value of this object" + patient. toString ())

Print result:

05-19 18:08:05. 621 25081-25081 /? I/xqxinfo: Call the primary constructor without Parameters
05-19 18:08:05. 621 25081-25081 /? I/xqxinfo: the second-level constructor of a parameter is called.
05-19 18:08:05. 621 25081-25081 /? I/xqxinfo: the second-level constructor of two parameters is called.
05-19 18:08:05. 621 25081-25081 /? I/xqxinfo: property value of the object XPatient {name = 'Alice ', age = 19, sex = 0}

Let's take a look at this. Do not assume that the master constructor is executed first, then a parameter is executed, and then the second-level constructor of the two parameters is executed.

The second-level constructor of the two parameters corresponding to the parameter of the created object is executed first. The constructor of the two parameters calls the constructor of a parameter, A parameter calls the main constructor.

Therefore, after the master constructor is executed, it will return the processing in the constructor of a parameter. After the constructor of a parameter is executed, then, process the two parameters in the constructor. Similar to recursion.

So print the result as shown in the above Code.

 

Ii. Inheritance of Classes

  There are several knowledge points about the Kotlin class that need to be crowdsourced security testing:

1. By default, Any class is inherited from Any (similar to the Object in Java) by the root)

2. By default, any class cannot be inherited (final)

3. Only classes declared open or abstract can be inherited.

 

Inheritance form:

 

Open class Animal (name: String) // The inherited class requires the open modifier class Person (name: String, surname: String): Animal (name) // inherits the class of the Animal class

 

 

 

Note: The method is a function.

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.