Nineth Chapter: Constructors and garbage collectors-objects of previous life

Source: Internet
Author: User

This series of articles is a personal reading note and summary content, any organization or individual may not be reproduced for commercial activities.

Nineth Chapter: Constructors and garbage collectors-objects of previous life
The object of Life and death:You must be responsible for the life cycle of the object, when to create, when to destroy (not eliminate, just give up), evaporate it by the garbage collector (GC), and reclaim the space it occupies; This section describes the contents of heaps, stacks, scopes, constructors, super constructors, null references, and so on;
two important areas of memory in Java:The living space Heap of the object (heap); method invocation and the variable's living space (stack); When the JVM starts, he takes a chunk of memory from the underlying operating system and executes the Java program in this section; all objects live on garbage-collected heaps; local variables are called stack variables;
instance variables and local variables:Instance variables are declared in classes rather than methods; represents the ' field ' of each individual object; the instance variable exists in the object to which it belongs; the parameters of local variables and methods are declared in the method; they are temporary and the lifecycle is limited to the period on which the method is placed on the stack;
The call method is a stack of the process, after the completion of the method, pop-up stack, the actual pressure stack is the stack block, it has the state of the method, including the execution to which line of programs and all the local variables;
A primitive local variable is only a reference to the object, exists on the stack, the object itself exists on the heap, and the knowledge stack is useful for understanding the valid scope (scope) of the variable, object establishment, memory management, threading (thread) and exception handling.
Main points:1. We relational stack and heap two kinds of memory space; 2. The instance variable is declared outside of the method in the class; 3. Local variables are declared on the parameters of the method or method; 4. All local variables exist in the stack of stacks corresponding to the stack; 5. Object references and primitive local variables of the main data type are placed on the stack 6. The object itself is on the heap, whether it is an instance variable or a local variable;
The instance variable exists on the heap space to which the object belongs:Primitive the instance variable of the primary data type, Java leaves space based on its size, and for instance variables of reference types, Java leaves the space needed for the reference, the space required by the instance variable is on the object, and if the instance variable reference type only declares an unassigned value, the heap space of the stored object leaves only the reference variable Space until it is assigned, and the reference variable points to the memory that is occupied by the assigned object;
the process of constructing an object:New Dog ();
is actually calling the dog constructor: constructor-like method, but not a method; it takes the program code that executes when new; the only way to invoke a constructor is to create a new class, which, strictly speaking, is the only way to invoke a constructor outside of the constructor. The compiler will write one for you without writing the constructor yourself;
constructor Function:no return type; The function name is the same as the class name;
Construct dog: A key feature of a constructor is that it executes before an object can be assigned to a reference, which means you have the opportunity to intervene before the object is used;
Initialization of new dog state: Most people use constructors to initialize the state of an object, assigning a value to an object's instance variable, and using a constructor to initialize the dog state, preferably by placing the initialized program code in the constructor and setting the constructor to the required parameter;
Constructors are not inherited.
There are constructors that require parameters, and note-it is best to have constructors that do not require parameters (but there are also classes that do not have parameterless constructors); The compiler will write a constructor that has no parameters when you do not set the constructor;
If a class has more than one constructor, this means that they are overloaded, and their arguments must be different (same as method overloads);
Main points:1 The instance variable is saved in the object to which it belongs. on the heap; 2) If the instance variable is a reference to an object, both the reference and the object are on the heap, and the 3 constructor executes the program code when the new object is created; 4 The constructor must have the same name as the class name and no return type; 5 You can initialize the state of the created object by using a constructor, 6 if the constructor is not written, the compiler will help you create a; 7 The default constructor has no parameters; 8 If you write a constructor, the compiler will not call; 9 It is best to have parameterless constructors that allow people to choose to use default values; 10 The overloaded constructor refers to the relationship between multiple constructors; 11 The parameters of two constructors must be different;
Constructors can be common, unspecified, private, private constructors are not inaccessible, and they are not accessible on behalf of the class;
constructor for parent class:When a new object is created, all inherited constructors execute; New, the constructor chain reaction is initiated--constructor chains (construction chaining); (even if abstract classes have constructors, abstract classes cannot be new, But it executes when the subclass creates an instance), using super to invoke the constructor of the parent class;
When the constructor executes, the first thing is to execute the constructor of the parent class, which is reflected to the class of object, and the process of constructing the reaction is similar to that of the method call, and is also a process of continuously pressing stack and retreating stack.
Example: (Code-animaldrive.java)

public class animal{
    private String name;
    private int age;
    
    public void SetName (String aname) {
        name = Aname;
    }
    Public String GetName () {return
        name;
    }
    public void setage (int aAge) {Age
        = AAge;
    }
    public int getage () {return age
        ;
    }
    Public Animal () {
        name = "Def";
        Age = 1;
        SYSTEM.OUT.PRINTLN ("initial animal");

    }
    Public Animal (String aname,int aAge) {
        name = Aname;
        age = AAge;
        SYSTEM.OUT.PRINTLN ("Initial animal with Paras");
    }
public class Dog extends animal{public
    Dog () {
        super ("haha", 5);
        System.out.println ("Initial dog");
    }
    public void Eat () {
        System.out.println ("Dog Eat");
    }

public class animaldrive{public
    static void Main (string[] args) {
        Animal ani = new Animal ();
        
        Dog Dog = new Dog ();
        Dog.eat ();
        
        System.out.println (Dog.getname ());
        System.out.println (Dog.getage ());
    }
This example also shows how to invoke the constructor of the parent class;
the only way to invoke the parent class constructor is to call Super ();Calling super () in your constructor puts the constructor of the parent class at the top of the stack; if we don't call super (), the compiler will help us add super () calls; (This can modify the sample code validation) Here's the thing to note Compiler help add must be no parameter version, if the parent class has multiple overloaded version of the constructor, only the version of no parameters will be called, if there is no this version, then need to actively invoke the other version, which is also recommended to provide a parameterless constructor reason;
The constructor of each subclass immediately invokes the constructor of the parent class; The call to Super () must be the first statement of the constructor, and super (Para) can receive parameters, corresponding to the call of the constructor with parameters of the parent class, (look closely at the example above to show how subclasses pass the super ( Name,age) to set the private variable of the parent class.
to invoke another constructor of the overloaded version from one of the constructors:Need to use this, which represents a reference to the object itself; this () can only be used in constructors and must be the first line of statements, and each constructor can optionally call super () or this (), but not at the same time; 1) Use this () to invoke the other of the same class from a constructor An external constructor; 2 this () can only be used in a constructor and must be the first line of statements; 3 super () and this () cannot be both;
How long the object will survive-the object lifecycle depends on the life cycle of the reference variable, and how long the variable will live. 1 The local variable will live only in the method of declaring the variable; 2 The life of the instance variable is the same as that of the object;
Life and scope:Lift: As long as the stack of the variable is still on the stack, the local variable is still alive; scope: The scope of a local variable is limited to the method in which it is declared; (another method is called in the method, the variable is alive, but the scope changes to the new method, until the new method is complete, and the scope is followed) that is: partial A variable can only be used in the execution of the method in which it is declared;
When the last reference of an object disappears, it becomes recyclable; There are three ways to release a reference to an object:1 refer to the permanent departure range; void Go () {Dog Dog = new Dog ();} 2) references are assigned to other objects, and 3 directly sets the reference to null;
the truth of NULL:Null is a combination of bytes that represents "null" (only the JVM knows what it is); a null reference cannot be manipulated (method calls, and so on); using a dot operator on a null reference will encounter an error such as NullPointerException in the executor, and when the variable is null, will have to wait to be garbage collection, the original place will also let out to others use;


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.