(new) Kotlin get up--4. Classes and objects

Source: Internet
Author: User
Tags abstract anonymous class definition constructor inheritance modifier
(new) Kotlin get up--4. Classes and Objects

This article declares :
This article is written by Coder-pig , want to know other content, visible "coder-pig pigsty "
Respect the work of the author, without my authorization, prohibit reprint. Reserved
"Kotlin Get Up" series Directory Address: http://blog.csdn.net/coder_pig/article/details/72851862 1.Any class

We all know that every class in Java has a default parent class for object , which is also in Kotlin, but not an object.
But the any class, although all are common parents of all classes, but the class composition is not the same, compared to know:

2. Class definition and Object instantiation

Kotlin differs from Java in that it allows you to define multiple classes in one file , and the class entity is optional , which is directly
class Test in this way, do not have to doubt the right, you can not write curly braces, of course, this is generally used to express the concept (nothing
Eggs). The instantiation of the class object and the invocation of the member method are also straightforward:

Here the property of the object is set **name, is actually called the auto -generated **setname () method, by the way, you
You can also customize the getter and setter methods of properties , do some filtering or some additional operations, such as:

And then there's a pit, which is if you write get () = Trueheight, you keep calling yourself and then OOM.
Someone on the net said to add a $ in front, but the measurement is not, if there is a solution must inform me.
In addition, you can also add privateto the get and set methods before you can suppress external calls. 3. Constructors (construction method)

The constructors in Kotlin are divided into three types: the main constructor

The rules are as follows : 1. If a non-abstract class does not declare any primary and secondary constructors, a public non-parametric main constructor is generated by default . 2. A class has only one main constructor , part of the class header , after the class name ,Constructor (argument list), 3. cannot contain any code in the main constructor , if you want to write some initialization code , you can write to the Init initialization code block .


use examples such as the following :

Auxiliary Constructors

The rules are as follows : 1. Written in a class, can have one or more , identified with the constructor keyword . 2. other auxiliary constructors can be called through this (), but any one of the secondary constructors must call the main constructor .


use examples such as the following :

Private Main constructor

is to add a privateto the main constructor , and then only instantiate the object through the auxiliary constructor .

use examples such as the following :

4. Inheritance

The previous section of common sense has also said that Kotlin inherits the parent class or implements the interface directly, using : quotation marks, if there are multiple
Can be separated by commas , and the previous section looks at the corresponding Java code we know the default modifier for the class is: public final,
means that the class is immutable , and if you want to do some rewriting, you need to add an open keyword before class,
The subclass construction method needs to implement the parent class construction method , and the modifier of the method is final , overriding a method, also need to
The method is preceded by the open keyword, and the override keyword is added before the overridden method; and you can use Super
Keyword to invoke a method in the parent class, which is the same as in Java.

use examples such as the following :

5. Interface

Interfaces in Kotlin are similar to JAVA8, support abstract methods , abstract properties , and support methods that contain implementations
The interface with the method in which the default is open is the same as Java using the interface declaration.

interfaces differ from abstract classes in that the interface cannot store state data and can have properties, but these properties must be
is abstract, or provides a custom implementation of accessors.

use examples such as the following :

In addition, if a class or interface that needs to be implemented contains a method with the same name, you can use <> to indicate which
The parent class method. Like what:

6. Abstract class

Similar to interfaces, the default is open , but for abstract members , you need to use the abstract keyword declaration.

use examples such as the following :

7. Internal classes, creation of anonymous inner classes

Classes can be nested within other classes, and internal classes cannot access external class members if they are simply nested.
If you want to access external members in an internal class, you need to declare them using the inner keyword.

examples of use are:

In addition to the anonymous inner class, the Kotlin automatically turns into the form of a lambda expression, such as setting a click event:

In Java:

In Kotlin:

Because the Onclicklistener anonymous inner class has only one OnClick method, it can be omitted if there is
Multiple methods require an anonymous inner class to be overridden, the object keyword is used, as in the following example:

8. Single-Instance objects

There are no static properties and methods in Kotlin, if you want to implement a function similar to singleton ,
You can use the keyword object to declare an object, and the constructor of the object cannot provide a constructor argument .
It is initialized at first use and can be used to provide constants or to share immutable objects .

examples of use are:

9. Associated Objects

In addition to the above Singleton, Kotlin also provides the companion object , using the companion keyword Declaration,
can be directly class. Member access members, somewhat similar to static members, but at run time they are still instance members of the entity,
In addition, the name of the associated object can be omitted when using the companion keyword.

use examples such as the following :

Of course, there may be some OCD patients who simply want to use static members and static methods , you can use the following keywords:

static members : @JvmField annotations: Generate static fields that are the same as this property lateinit keyword: lazy initialization, previous section defining empty variables Speaking ~ Const Keywords: Converting the Kotlin property to a static field in Java (defining constants)

static methods : @JvmStatic annotations: Generate a corresponding static method in a singleton object and an associated object

use examples such as the following :

10. Data Class

is a class that represents data only, declared by using data, which is implemented by default based on the constructor method:
toString (), componentn(), copy(), equals(), and hashcode() methods,
In addition, properties that are not defined in the construction method are not produced in the result of ToString ().
The data class can be compared directly using = = .

use examples such as the following :

11. Enumerating Classes

Enumerations in Kotlin are basically similar to those in Java, declared as enum classes with enum
The most basic usage is to implement type-safe enumeration, for example, to show you that from Monday to Sunday, large people will use 1-7,
If an exception occurs and the user enters 0 or 8, the enumeration can be viewed as limiting the type of data entered
Can only be one of the enumerations, thus implementing the so-called type safety.

use examples such as the following :

Output :

In addition, you can also get an array by valueOf ("name") class match or values () .
Then traverse the ~ 12. Enclosing class

To restrict the hierarchy of a class, the value can only be a type in the collection , not any other type,
Can be understood as an "extended enumeration class ," but somewhat different from enumerations:
The instances in the enumeration are unique , and the enclosing classes can have many instances , they can have different states,
Use the keyword sealed declaration (the inner class is the subclass of itself) and the keyword cannot be decorated with an interface or abstract class , it will report
Waring, but no compilation errors occur. Another thing to differentiate:
Direct subclasses must all be written in the enclosing class ... the extension of a enclosing class subclass can be anywhere, without needing to be in the same file .
The most important benefit of using the sealed class is that when you use the when expression, you can ensure that the declaration can be overwritten in all cases and no longer need to be used
else scenario.

PS: In Kotlin 1.1, the use of data class inheritance is allowed.

use examples such as the following :

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.