Java Programming Ideas (v. Initialization and cleanup)

Source: Internet
Author: User
Tags compact

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

Initialization and cleanup are just two issues that involve security. C + + introduces the concept of a constructor, a special method that is called automatically when an object is created. Java also employs a constructor and provides additional "garbage collector". For memory resources that are no longer in use, the garbage collector can automatically release it.

1, use the constructor to ensure initialization. When creating an object, if its class has a constructor, Java will automatically invoke the appropriate constructor before the user has the ability to manipulate the object, guaranteeing initialization. Constructors that do not accept any parameters are called default constructors, and the term parameterless constructor is commonly used in Java documents.

Suppose that a class tree has a constructor that takes an integer variable to represent the height of the tree, and it can create an object like this.

New Tree (12);

If the tree (int) is the only constructor in the tree class, the compiler will not allow you to create the tree object in any other way.

Constructors help reduce errors and make your code easier to read. Conceptually, "Initialize" and "create" are independent of each other, but in the above code, you cannot find a call to the Initialize () method. In Java, "Initialize" and "create" are bundled together, and they cannot be separated.

A constructor is a special type of method because it has no return value, which is significantly different from the null return value. For a null return value, although the method itself does not automatically return anything, it still chooses to let it return something else. The constructor does not return anything. You have no choice (the new expression does return a reference to the new object, but the constructor itself does not have any return values).

2, method overloading. When an object is created, it also takes a name for the storage space allocated to the object. The so-called method is to get a name for an action. By using a name, you can refer to all objects and methods. Differentiate overloaded methods. That is, each overloaded method must have a unique list of parameter types.

An overload that involves a base type. The base type can be automatically promoted from a "smaller" type to a "larger" type. For example, if the incoming parameter is constant 5, and an overloaded method accepts an int parameter, it will be called. If the data type passed in (the actual parameter type) is less than the formal parameter type declared in the method, the actual data type is promoted.  The char type is slightly different, and if you cannot find a method that exactly accepts the char parameter, the char is promoted directly to the int type. The method accepts a smaller base type as a parameter, and if the actual parameter passed in is larger, you have to listen to the type conversion to perform a narrowing conversion (explicitly). Otherwise the compiler will make an error.

It is not feasible to differentiate overloaded methods with return values. For example, sometimes we just call methods. such as f (); no return value is required, in which case the compiler cannot tell the exact method that I am using by the return value.

3, the default constructor. If there are no constructors in the write class, the compiler will automatically help you create a default constructor. If you have already defined a constructor (with or without parameters), the compiler will not automatically help you create the default constructor.

4. This keyword. This keyword can only be used inside a method, indicating a reference to the "object that called the method". The usage of this and other object references are not different. If you call another method of the same class inside a method, you do not have to use this to call directly.

 Public class user{    void  pick () {};    void  pit () {pick ();}    }

You need to use the This keyword only if you need to explicitly indicate a reference to the current object. The This keyword is also useful when passing the current object to another method.

class Person {   publicvoid  eat (Apple apple) {        Apple peeled = apple.getpeeled ();
System.out.println ("Yummy"); } }
Class peeler{
Static Apple Peel (Apple apple) {
return Apple;
}
}
Class Apple {
Apple getpeeled () {
Return Peeler.peel (this);
}
}
public class passingthis{
public static void Main (string[] args) {
New person (). Eat (New Apple ());
}
}

5. Call the constructor in the constructor. Sometimes multiple constructors are written for a class. Sometimes you might want to call another constructor in one constructor to avoid repeating the code. This keyword can be used to do this.

public class flower{
Flower (int petals) {}
Flower (String ss) {}
Flower (String s,int petals) {
This (petals);
This (s); Although you can call a constructor with this, you cannot call two. In addition, the constructor must be called at the very beginning, or the compiler will error
}
}

Sometimes the name of the passed parameter and the name of the data member of the class are the same, and this can be used to resolve the ambiguity.

And, in addition to constructors, the compiler prohibits calling constructors elsewhere.

6, the meaning of static. Static is the method without this. A non-static method cannot be called inside the static method. It is also possible to invoke the static method only through the class itself, without creating any objects. The static method has the semantics of the global function. When using the static method, this is not done by "object-oriented messaging" because it does not exist. If you have a large number of static methods in your code, you should reconsider your design.

7, Cleanup: End processing and garbage collection. Assume that your object (not using new) obtains a "special" area of memory. Because the garbage collector knows only to release memory that is allocated through new, it does not know how to release this "special" memory for that object. To cope with this situation, Java allows you to define a method named Finalize () in the class. It works "hypothetically": once the garbage collector is ready to release the storage space that the object occupies, its finalize () method is called first, and the memory occupied by the object is actually reclaimed when the next garbage collection action occurs. So if you plan to use Finalize (), you can do some important cleanup at the time of garbage collection.

There is a programming pitfall here: Finalize () is not a destructor in C + +. In C + +, objects are bound to be destroyed (if the program is not defective). But objects in Java are not always garbage collected. In other words: In Java, 1, objects may not be garbage collected, 2, garbage collection is not equal to "destruction." As long as the program is not on the verge of storage space, the space occupied by the object is always not released. If the program execution finishes and the garbage collector has not freed up storage space for any objects you create, those resources will be returned to the operating system as the program exits. Because garbage collection itself has a cost, you don't have to pay for it if you don't use it.

Garbage collection is only related to memory. The only reason to use the garbage collector is to reclaim memory that the program is no longer using. Local methods allow Java to invoke non-Java code. Local methods now support only C and C + +. But C and C + + can call code written in other languages. So you can actually call any code. In non-Java code, the malloc () function family of C may be called to allocate storage space, and unless the free () function is used, storage space is not freed, causing a memory leak. So call it in Finalize () with a local method.

Java virtual machines do not face memory exhaustion, and it is not a waste of time to perform garbage collection to recover memory. If you want to take a look at the garbage collection situation, you can use System.GC () to force the finalization action.

8. How the garbage collector works. In general, the cost of allocating objects on a heap is very high. However, the garbage collector has a noticeable effect on increasing the speed of object creation. The garbage collector's intervention, when he is working, will reclaim space on one side, making the objects in the heap compact, so that the "heap pointer" can be easily moved closer to the carousel (in some Java virtual machines, the implementation of the heap is much like a conveyor belt, where each new object is assigned to move forward one grid) at the beginning.

How to determine if the object is dead? The garbage collector determines that any "live" object must eventually be traced back to the reference it survives in the stack or static storage area. This reference chain may pass through several object hierarchies. As a result, all the "live" objects can be found by traversing all references, starting from the stack and the static store. For each reference that is discovered, you must trace the object it references, and then all references that this object contains. This is done repeatedly, knowing that the network formed by "references from stacks and static stores" is all accessed.

How the found surviving objects are handled depends on the different Java Virtual machine implementations. There is a name of stop-copy. Pauses the program's run, and then copies all the surviving objects from the current heap to the other heap. All that is not copied is rubbish. When objects are copied to the new heap, they are one next to each other, keeping the new heap in a compact arrangement. But sometimes this method is not easy to use, first of all it has to have two heaps, so wasted a lot of space. The second is that after the program is stable, only a small amount of garbage is generated, but replication still has to copy all the memory from one place to another. To avoid this situation, if there is no new garbage generation, the Java virtual machine will be converted to another mode, which is called tag-sweep. The idea is also to go from the stack and the static store, traverse all references, and find all the surviving objects. Whenever it finds a surviving object, it sets a tag for the object. No objects are recycled during this process. The cleanup action will only begin when all marks are completed. During the cleanup process, objects that are not marked will be freed and no duplication work will occur. So the rest of the heap space is discontinuous. The garbage collector has to be re-organized if it wants to be in a contiguous space. Strictly speaking, stop-replication requires that all surviving objects be copied from the old heap to the new heap before releasing the old object. However, some objects occupy a large amount of memory, so they occupy a separate block. With the block, the garbage collector can copy objects into the discarded blocks when it is recycled. Each block uses the corresponding algebra to record whether it is still alive. In the cleanup process, large objects are not copied (only their algebra is incremented), and the chunks that contain small objects are copied and organized.

There are many additional techniques in the Java Virtual machine to increase speed. This is especially relevant to loader operations. Technology known as the "instant" compiler. This technology can translate all or part of the program into local machine code, the program speed can therefore be improved. When a class needs to be loaded, the compiler finds its. class file first. The byte code of the class is then loaded into memory. At this point, there are two options, one is to let the immediate compiler compiles all the code, but there are two defects, this loading action scattered in the program life cycle, the accumulation of more time, and will increase the length of executable code, which will lead to page scheduling, thereby reducing the program speed. Another approach, called lazy evaluation, means that the immediate compiler compiles code only when necessary. In this way, code that will never be executed may not be compiled by the "instant" compiler at all. Java hotspot Technology in the new JDK uses a similar approach, and the code performs some optimizations each time it is executed, so the more times it executes, the faster it will be.

9. Initialization of the member. The order of initialization is a static object, and then a "non-static object".

Constructor initialization. The constructor can be used for initialization, but automatic initialization will occur before the constructor is called.

Initialization of static data. Static data consumes only one copy of the storage area, regardless of how many objects are created. The static keyword cannot be applied to local variables, so it can only be used for fields. If a domain is a static base type domain, and it is not initialized. Then it will get the standard initial value of the basic type. If it is an object reference, then its default initial value is null. Static initialization actions are performed only once: When an object of this class is first generated, or when a static member belonging to that class is first accessed (even if the object of that class has never been generated).

Array initialization. An array is just the same type of object sequence or primitive type data series that is encapsulated together with an identifier name. Only one reference to an array is owned. The creation of an array is performed at run time. Variable parameter list. Provides a convenient syntax for creating objects and calling methods. Because all classes are directly or indirectly inherited from the object class, you can create a method that takes an object array as a parameter.

The enumeration type. When an enumeration is created, the compiler automatically adds some useful features, such as the ToString () method, to display the name of an enum instance. The ordinal () method, which represents the order of declarations for a particular enum constant. static values (), used to produce an array of these constant values in the order in which they are declared in the enum constant.

Java Programming Ideas (v. Initialization and cleanup)

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.