Thinking in Java 4th chap5 notes-initialization and cleanup

Source: Internet
Author: User
Tags array definition

Initialize and clean up 1. if the this keyword has two objects a and B of the same type, how can we make these two objects call the peel method at the same time? For example: Banana a = new Banana (); banana B = new Banana;. peel (1); B. peel (2); if there is only one peel method, how does it know whether it is called by a or B? For ease of use, object-oriented syntax to write code, that is, "send messages to objects"; the compiler has done some background work, he secretly passed the "reference of the operated object" as the first parameter to peel-> so the call of the above two methods became like this:. peel (a, 1), B. peel (B, 1); this is an internal representation. Although we cannot write code like this and try to compile it, it does help you understand what actually happens. If you want to get a reference to the current object within the method, because this reference is passed by the compiler "secretly", there is no identifier available; but there is a special Keyword: this; this keyword can only be used inside a method, indicating a reference to the object that calls the method; this reference of the current method will be automatically referenced by other methods of the same class-> this keyword is used only when the reference to the current object needs to be explicitly specified; if you need to return a reference to the current object, you will often write the following in the return statement: return this; Note: Someone insisted that this be placed before each method call and field reference, it is "clearer and clearer ". But never do this. One of the reasons we use advanced languages is that it helps us do something. If you put this in unnecessary places, you will be overwhelmed by the readers, because the code written by others will not be used everywhere. Following a consistent and intuitive programming style can save time and money. 1. this is used to return a reference to the current object, so it is easy to perform multiple operations on the same object in a statement; 2. you must call this 3 only when necessary. the constructor is called in the constructor. this adds the parameter list to generate a clear call to a constructor that complies with this list (except the constructor, the compiler prohibits the constructor from calling any other method) 4. solve the problem that the parameter name is the same as the data member name, and the data member uses this. 5. the static method is the method without this, and the non-static method cannot be called within the static method (this is not completely impossible, if you pass an object reference to a static method (the static method can create its own object), and then use this reference (same effect as this) you can call non-static methods and access non-static data members. But to achieve this, you only need to write a non-static method); in turn, you can; you can call the static method only through the class itself without creating an object, this is actually the main purpose of the static method. Some people think that static is not object-oriented because it does have the semantics of global functions. When using the static method, because this does not exist, therefore, it is not done by "sending messages to objects". Indeed, if there are a lot of static methods in the code, you should reconsider your design; however, the concept of static is actually used, and is often used. Leave it to the theory that it is really object-oriented. 2. end cleaning and garbage collection 1. objects may not be reclaimed. 2. garbage collection is not equivalent to structure 3. garbage collection is only related to memory. Garbage collection itself also has overhead finalize: Assuming the working principle: Once the garbage collector is ready to release the storage space occupied by objects, it will first call the finalize method, in addition, the memory occupied by objects will be recycled only when the next garbage collection action occurs.; [However, if "Garbage Collection" does not happen, it cannot be released. This policy is appropriate as long as the program is not on the verge of using up storage space; the total space occupied by objects cannot be released, because garbage collection is overhead.] objects are allocated with storage space in a way other than object creation: it is because the C language may be used when the memory is allocated, which mainly happens when the "local" method is used; the local method is a method for calling non-Java code in Java. Currently, local methods only support C/C ++, but they can call code written in other languages, so they can actually call any code. In non-Java code, it may call a series of malloc functions similar to C to allocate storage space, and the storage space will not be released unless the free function is called, resulting in Memory leakage; of course, free is a C/C ++ function, so you need to call it using a local method in finalize. [remember: no matter whether it is garbage collection or termination, it will not always happen. If Java Virtual Machine (jvm) does not face memory depletion, it will not waste time executing garbage collection to restore the memory.] 3. java heap Model 1. in the heap implementation of some java virtual machines, it is more like a conveyor belt. Every time a new object is allocated, it moves one cell forward. The object storage space is allocated very quickly, java's "heap" pointer is just a simple move to an unallocated area; (C ++'s heap is like a yard, and every object is responsible for managing its own territory. After a while, objects may be destroyed, but the site must be reused). However, Java heap does not work exactly like a conveyor belt. Otherwise, frequent Memory Page scheduling will occur, significantly affecting performance; after garbage collection is involved, when it is working, it recycles space while compress the objects in the team, so that the "heap Pointer" can easily move closer to the start of the conveyor belt; avoid page errors as much as possible-> rearrange objects through the garbage collector to implement a heap model with infinite space available for allocation. 4. garbage collection mechanism: 1. reference count: When the Garbage Collector traverses the list containing all objects, it finds that the reference count of an object is 0, which is to release the occupied space. However, for cyclic references between objects, "The object should be recycled, but the reference count is not 0". For the Garbage Collector, it takes a lot of work to locate such a cross-referenced object group. 2. faster mode: For any "active" object, it can be traced back to its reference that is actually stored in the stack or static storage area. Therefore, if you start from the stack and static storage area, traverse all references to find all living objects. Stop-copy mark-clean two methods the program will pause adaptive, generational, stop-copy, mark-cleanup Garbage Collector 3. many additional technologies of Java Virtual Machine-> JIT (just in time) compiler technology-> Java HotSpot technology of the new JDK 6. initialization 1. method local variables, error guarantee during compilation. [of course, the compiler can assign a default value to local variables, but uninitialized local variables are more likely to be neglected by programmers, therefore, using the default value will cover up such errors. Therefore, it is mandatory for programmers to provide an initial value and often find bugs in the program.] 2. within the class, the order in which variables are defined determines the initialization order. Initialization is obtained before any methods (including constructors) are called. static Data initialization: no matter how many objects are created, static data occupies only one storage area.-> static data Initialization is performed only when necessary-> 4. the constructor can be regarded as a static method. The static method of the Class Object/Category class is created for the first time. class-> static initialization, only initialize once when the class is loaded-> new, allocate enough storage space for the object on the heap-> 0 for this storage space, all basic types are set to the default value. null is referenced. Execute all initialization actions that appear in the field definition. Execute the constructor. Execute the constructor. static {}, static clause; {}, instance initialization clause; www.2cto.com 6. array initialization int [] array ={}; int [] array = new int [] {}> the former can only be used in the array definition, while the latter can pass the variable parameter list, such as int... args, String... args; variable parameter lists make the overload process more complex-> for example, f (Integer... args); f (Long... args)-> when calling f (), the compilation fails, because you do not know which f method to call-> you can add a non-variable parameter to each method-> you should always use the variable parameter list only in one version of the method, or it is not used at all; 7. enum enumeration is a class and has its own method. The enum name can be added clearly to indicate what the program is intended for. When an enum is created, the compiler automatically adds some useful features, for example, if you create a toString method, the name of each enum instance is conveniently displayed. The ordinal method is also created to indicate the Declaration Order of a specific enum constant. The static values Method, it is used to generate an array composed of these constants according to the declared order of enum constants. It is an excellent combination with switch. It is used directly for the obtained types without too much consideration, use enum as another way to create data types. Before enumeration, we need to create an integer constant set, however, these constant values do not limit their own values to the range of the constant set, so they are more risky and more difficult to use; of course, in the past, this enumeration security mechanism was: (I personally think it can still meet the requirements, but there are no useful features added by the compiler, and there will be problems during serialization) public class Oriented {private int value; // two security non-final enumeration public static final Oriented ORI = new Oriented (1); public static final Oriented OR2 = new Oriendted (2 ); // private constructor private Oriented (int v) {value = v ;}} 8. the garbage collector does increase the runtime overhead, and the Java interpreter is always slow. Over time, java has made great progress in performance, however, the speed problem is still an obstacle in some programming fields. 9. some source code package com. book. chap5.initAndDestroy;/***** use Finalize to verify the final condition * <p> in this example, the final condition is: all book objects should be checkin in garbage collection; in the main method, one book was not checked in and found by the finalize method, output Message </p> ** @ author landon * @ since JDK1.6 * @ version 1.0 2012-4-12 **/public class FinalizeUsage {public static void main (Stringargs) {Book novel = new Book (true); novel. checkIn (); new Book (true); // force the final action [of course, you can also execute the program repeatedly, assuming that the program will allocate a large amount of storage space, eventually, the wrong Book] System can be found. gc () ;}} class Book {private boolean checkOut; public Book (boolean checkOut) {this. checkOut = checkOut;}/*** check in. Books can be recycled only after being checked */public void checkIn () {checkOut = false ;} @ Override protected void finalize () {if (checkOut) {System. out. println ("Error: has book checked out"); try {// call the finalize method super of the parent class. finalize ();} catch (Throwable e) {e. printStackTrace () ;}}} package com. book. chap5.initAndDestroy;/*** initial enum enumeration usage ** @ author landon * @ since JDK1.6 * @ version 1.0 2012-4-12 **/public class SimpleEnum {public static void main (Stringargs) {Spiciness howHot = Spiciness. MEDIUM; // print enumeration. The toString method has implemented System. out. println (howHot); // ordinal starts from 0 in the declared order for (Spiciness spiciness: Spiciness. values () {System. out. println (spiciness + "ordinal:" + spiciness. ordinal ();} testSwitchEnum (Spiciness. MILD); testSwitchEnum (Spiciness. HOT); testSwitchEnum (Spiciness. FLAMING);} // test the combination of enum and switch public static void testSwitchEnum (Spiciness spiciness) {switch (spiciness) {// note that the case must be NOT and must be an unrestricted enumeration name. [the spiciness type has been determined to be an enumeration Spiciness. You do NOT need to add Spiciness. NOT, it is superfluous to draw a snake], NOT Spiciness. NOT, otherwise, The qualified case label Spiciness will be reported during compilation. NOT must be replaced with the unqualified enum constant NOT case NOT: System. out. println ("not"); break; case MILD: System. out. println ("mild"); break; case MEDIUM: System. out. println ("medium"); break; case HOT: case FLAMING: default: System. out. println ("too hot") ;}}// enumeration declaration enum Spiciness {// constant, uppercase NOT, MILD, MEDIUM, HOT, FLAMING} package com. book. chap5.initAndDestroy;/***** variable parameters ** <p> you can use any type of parameters in the Variable Parameter List, including basic types </p> ** @ author landon * @ since JDK1.6 * @ version 1.0 2012-4-12 **/public class VarArgs {public static void main (Stringargs) {printArgsClass (1); // output class [I getClass, which generates the class System of the object. out. println (new int [0]. getClass (); f (1, 'A'); // The method f (float, Character []) is ambiguous for the type VarArgs/f ('A ', 'B');} public static void printArgsClass (intargs) {System. out. println (args. getClass ();} // be cautious when using the variable parameter list; it is very likely that there are ambiguous calls-> which leads to the compilation error public static void f (float f, Characterargs) {System. out. println ("first method");} public static void f (Characterargs) {System. out. println ("second method ");}}

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.