Understanding of the associated objects of Kotlin

Source: Internet
Author: User
Associated Objects analogy Java

Do you still remember static statically members in Java? Attributes and methods declared as static idioms are initialized at class loading, parsing, and then their lifecycle is bound to the life cycle of the class.

1. This allows certain variables and methods in a class to be bound to the class, rather than bound to an object, to increase its life cycle.

2. This allows objects of this class to share this variable and method without allocating resources for each object, saving resources. How did Kotlin deal with that?

There is no static variable in Kotlin, so, it uses the associated object to mimic the role of static variables in Java. The associated object is also initialized in class loading, and the same life cycle is consistent with the life cycle of the class and can also be passed directly through the class name. (Attribute,method) to invoke. Multiple objects of the class share the associated object.

Why is there a single object in Kotlin to include all static resources?

In fact, the answer can be obtained from the class loading mechanism in Java, during the initialization phase of the class loading phase, the init () function is called to initialize in the order of static properties and static initial code blocks, where the associated object can be estimated as encapsulation of the init () function.

Language is actually the same, we learn to be good at analogy and analysis, so regardless of the face of any language, you can quickly get started, easy.

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.