Diagram & Java initialization and cleanup: constructors must know

Source: Internet
Author: User
Tags knowledge base

Writer:bysocket (mud and brick pulp carpenter)

Micro-Blog: Bysocket

Watercress: Bysocket

FaceBook: Bysocket

Twitter: Bysocket

In object-oriented programming, programmers should be concerned with " resources ". Like what

?
1 <font color="#000000">String hello = "hello"; </font>

In the code, we are in the memory of the string type of Hello, it has a life cycle . In its life cycle, initialization (initialization) and Cleanup (cleanup) are two important links. Especially in C programs , many bugs appear in the object initialization and cleanup process. This can cause some procedural security problems.

"Think in Java" says:

With the development of the computer revolution , "unsafe" programming has become one of the main reasons for the high cost of programming.

first, stack and heap

In Java development, two areas of memory are cared for by objects: The object 's living space is heap (heap) - method calls and local variables (also called stacks Variable) is a living space stack (stack).

Ii. What is a constructor, default (no parameter) constructor

To ensure that the object is initialized successfully, Java introduces the constructor (Constructor) like C + +, which is a special method that is called automatically when the object is created. Naturally, Java provides additional GC (garbage collector), and the garbage collection mechanism automatically frees resources for resources that are no longer in use. When Java creates a new object through the class constructor, it calls its constructor to initialize before using this object. Such as:

?
12345678910 <font color= "#000000" > public class Voidconstructor { &NBSP;&NBSP;&NBSP;&NBSP;  &NBSP;&NBSP;&NBSP;&NBSP; voidconstructor () { &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP; //constructor &NBSP;&NBSP;&NBSP;&NBSP; } &NBSP;&NBSP;&NBSP;&NBSP;  &NBSP;&NBSP;&NBSP;&NBSP; void Voidconstructor () { &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP; //void method, not constructor &NBSP;&NBSP;&NBSP;&NBSP; } }</FONT>

1. Default constructor

Here, Voidconstructor is a class, if you need to create a Voidconstructor object as long as

?
1 <font color="#000000">VoidConstructor constr = new VoidConstructor();</font>

Invoking the above code allows you to generate a Voidconstuctor object from this default constructor (i.e., the parameterless constructor ). The code plots are as follows

2, note that the constructor is a special method that takes the same name as the class names . It does not have a return value , which differs from the void method whose return value is empty . Here, the Void method name is also not canonical, should be " each method first letter lowercase ", also generally not the same as the class name.

Also, the compiler generates a default constructor, even if your class does not write a constructor.

third, with the parameter constructor

Here's an example with a parametric constructor:

?
12345678910111213141516171819 /** * @author Jeff Lee * @since 2015-9-7 16:54:19 * 带参数简单构造器的展示 */public class SimpleConstructor2 {    public static void main(String[] args) {        for (int i = 0; i < 10; i++) {            new Child2(i);        }    }}// Child类class Child2 {    Child2(int i) {// 带参数的Child类构造器        System.out.print("Child init " + i + " ");    }}

In Eclipse, right-click Run AS- java application:

The above Child2 (int) is the only constructor for the child class, which is not a good time to create objects in the compiler with new Child2 ().

Therefore, the constructor helps to avoid code errors in development.

In both, the constructor can be used to initialize the resource . Where the creation of objects is bundled with the initialization of resources.

Take a Break ~ look at the ads:

The Open source code is on my github oh- https://github.com/JeffLi1993 Author message " please hand cheap, point project Star, support support please please"

Iv. Constructors in succession

When an object is created, each constructor is called by the inherited object. Let's say the following example:

?
123456789101112131415161718192021 /** * @author Jeff Lee * @since 2015-9-10 08:56:18 * 继承中的构造器的案例 */public class ChildConstructor extends PersonConstructor{    ChildConstructor() {<br>                  //super();<br>        System.out.println("Making a Child Modle...");    }        @SuppressWarnings("unused")    public static void main(String[] args) {        ChildConstructor childConstructor = new ChildConstructor();    }}class PersonConstructor {    PersonConstructor() {        System.out.println("Making a Person Modle...");    }}

The main function results in the following operation:

1. First analyze the following class UML, childconstructor inherit personconstructor,personconstructor inherit Object:

2. Super keyword, super is used to invoke the constructor of the parent class. If there is no super keyword in the subclass, the compiler automatically adds the default super () method. Therefore, subclasses call the parent class constructor through the super () method.

3. Then the main function, through the new directive , initiates the creation of the childconstructor object. When the subclass Childconstructor Constructor executes, the first thing calls the parent class through Super (), which in turn has a ripple effect to the OBJERCT class. Therefore, the print console first outputs "parent class first initialized".

This process is the constructor chain (Constructor Chaining), which is the child object is-a the Person object and also is-a the object. If you create a child object, you also create a part of the person object and object.

4. The process Flowchart is detailed (the diagram is the object reference on the stack block):

V. Summary

Although the constructor is small, the key is still critical.

This article summarizes:

1. Default constructor

2. A parametric constructor

3. Constructors in succession

and the 1th Knowledge Base supplement.

Welcome to click on my blog and github-blog to provide RSS Subscription Oh!

———-http://www.bysocket.com/————-https://github.com/JeffLi1993 ———-

Diagram & Java initialization and cleanup: constructors must know

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.