Thinking in Java: Chapter 5 initialization and cleanup

Source: Internet
Author: User

5.1 use the constructor to ensure initialization.

When defining a class, if no constructor is defined, the system automatically creates a non-parameter Constructor (default constructor). If the constructor has been defined, no constructor is automatically created.

5.2 method overload

When a method is overloaded, the parameter type list is used to differentiate the methods. The options include parameter type, order, and quantity;

When an overload involving a basic type is involved, the basic type can be automatically upgraded from a "smaller" type to a "larger" type. That is to say, the method accepts a small basic type as a parameter. If the input actual parameter is large, you have to perform a narrow conversion through type conversion.

5.3 default constructor

5.4 This keyword

In order to write code with simple and object-oriented syntax-that is, "send messages to objects", the compiler has done some background work. It indicates that the "reference of the operated object" is passed to the class as the first parameter, so the following method call is:

//: initialization/BananaPeel.javaclass Banana { void peel(int i) { /* ... */ } }public class BananaPeel {  public static void main(String[] args) {    Banana a = new Banana(),           b = new Banana();    a.peel(1);    b.peel(2);  }} ///:~

In this case, the call of the two methods in the compiler changes:

Banana. Peel (A, 1)

Banana. Peel (B, 2)

In addition, if you write multiple constructors for a class, you may want to call another constructor in one constructor to avoid code duplication. In this case, use the this keyword. However, the constructor can be called only once at the beginning of the constructor.

5.5 cleanup: final processing and garbage collection

Java provides the Finalize method for classes. This method can be used to clean up garbage collection.

In this regard, we need to make a description of the garbage collection: the object may not be garbage collection; the garbage collection is not equal to the "analysis structure"; the garbage collection is only related to the memory.

At this point, we can know that if Java's native method (for example, Calling C ++ new object) is used, if C ++ Delete is not explicitly called, the garbage collector cannot recycle this object. In addition, some other operations you do may not be clear. For example, if you draw an image on the screen, if it is not erased, the image will always be on the screen.

The following is an example of checking in a book upon borrowing. All book objects should be checked in before being recycled as garbage:

//: initialization/TerminationCondition.java// Using finalize() to detect an object that// hasn't been properly cleaned up.class Book {  boolean checkedOut = false;  Book(boolean checkOut) {    checkedOut = checkOut;  }  void checkIn() {    checkedOut = false;  }  protected void finalize() {    if(checkedOut)      System.out.println("Error: checked out");    // Normally, you'll also do this:    // super.finalize(); // Call the base-class version  }}public class TerminationCondition {  public static void main(String[] args) {    Book novel = new Book(true);    // Proper cleanup:    novel.checkIn();    // Drop the reference, forget to clean up:    new Book(true);    // Force garbage collection & finalization:    System.gc();  }} /* Output:Error: checked out*///:~

The garbage collector starts to work when the memory is about to run out and recycles objects that are no longer in use. The implementation of heap in many virtual machines is as follows: it is more like a conveyor belt. Every time a new object is allocated, it moves one cell forward. To do this, the garbage collection period requires memory sorting. There are two methods: "Stop-Copy" and "mark-clean ". For a relatively stable Program (no new garbage is generated), it enters the "mark-sweep" mode.

In addition, to improve the speed, Java virtual machine uses the "juse-in-time (JIT)" compilation technology to compile classes first. class file, and then load the byte code of the class into the memory. There are two methods: one is to let the instant compiler compile all the code; the other is to use the inertia evaluation, which means that the instant compiler only compiles the code when necessary.

5.6 initialize a member

5.7 constructor Initialization

To sum up the object creation process, assume that the class named dog is:

1) even if the static keyword is not displayed, the constructor is actually a static method. Therefore, when a dog-type object is created for the first time (the constructor can be regarded as a static method), or when the static method/static field of the Dog class is accessed for the first time, the Java interpreter must search for the class path to locate the dog. class file.

2) load it into dog. Class (this will be learned later, and a class object will be created). All static initialization actions will be executed. Therefore, static Initialization is only performed once when the class object is loaded for the first time.

3) when you use new dog () to create an object, you will first allocate enough storage space for the dog object on the heap.

4) This bucket is cleared, which automatically sets all the basic data types in the dog object to the default value (0 for the number, for Boolean and struct types), and the reference is set to null.

5) execute all initialization actions that appear in the field definition.

6) execute the constructor. As we can see in Chapter 7th, this may involve many actions, especially when it comes to inheritance.

Display static initialization:

//: initialization/Spoon.javapublic class Spoon {  static int i;  static {    i = 47;  }} ///:~

The code after static is the same as the static initialization action. This code is only executed once: when an object of this class is generated for the first time, or when the static data member of that class is accessed for the first time.

Non-static instance initialization:

//: initialization/Mugs.java// Java "Instance Initialization."import static net.mindview.util.Print.*;class Mug {  Mug(int marker) {    print("Mug(" + marker + ")");  }  void f(int marker) {    print("f(" + marker + ")");  }}public class Mugs {  Mug mug1;  Mug mug2;  {    mug1 = new Mug(1);    mug2 = new Mug(2);    print("mug1 & mug2 initialized");  }  Mugs() {    print("Mugs()");  }  Mugs(int i) {    print("Mugs(int)");  }  public static void main(String[] args) {    print("Inside main()");    new Mugs();    print("new Mugs() completed");    new Mugs(1);    print("new Mugs(1) completed");  }} /* Output:Inside main()Mug(1)Mug(2)mug1 & mug2 initializedMugs()new Mugs() completedMug(1)Mug(2)mug1 & mug2 initializedMugs(int)new Mugs(1) completed*///:~

This syntax is required for initialization that supports "anonymous internal classes", but it ensures that some operations will happen no matter which display constructor is called. The output shows that the instance initialization clause is executed before the two constructors.

5.8 array Initialization

Int [] a1 = {1, 2, 3, 4, 5, 6,} // The last comma.

Int A2 [];

A2 = A1; // A2 is a reference of A1.

In addition, Arrays can be initialized with new in the middle of the program. For example, a1 = new int [Rand. nextint (20)]

The variable parameter list has two forms: the old version and the new version (Java se5 ):

//: initialization/VarArgs.java// Using array syntax to create variable argument lists.class A {}public class VarArgs {  static void printArray(Object[] args) {    for(Object obj : args)      System.out.print(obj + " ");    System.out.println();  }  public static void main(String[] args) {    printArray(new Object[]{      new Integer(47), new Float(3.14), new Double(11.11)    });    printArray(new Object[]{"one", "two", "three" });    printArray(new Object[]{new A(), new A(), new A()});  }} /* Output: (Sample)47 3.14 11.11one two threeA@1a46e30 A@3e25a5 A@19821f*///:~

New Version:

//: initialization/VarargType.javapublic class VarargType {  static void f(Character... args) {    System.out.print(args.getClass());    System.out.println(" length " + args.length);  }  static void g(int... args) {    System.out.print(args.getClass());    System.out.println(" length " + args.length);  }  public static void main(String[] args) {    f('a');    f();    g(1);    g();    System.out.println("int[]: " + new int[0].getClass());  }} /* Output:class [Ljava.lang.Character; length 1class [Ljava.lang.Character; length 0class [I length 1class [I length 0int[]: class [I*///:~

5.9 Enumeration type

//: initialization/Spiciness.javapublic enum Spiciness {  NOT, MILD, MEDIUM, HOT, FLAMING} ///:~

//: initialization/EnumOrder.javapublic class EnumOrder {  public static void main(String[] args) {    for(Spiciness s : Spiciness.values())      System.out.println(s + ", ordinal " + s.ordinal());  }} /* Output:NOT, ordinal 0MILD, ordinal 1MEDIUM, ordinal 2HOT, ordinal 3FLAMING, ordinal 4*///:~

//: initialization/Burrito.javapublic class Burrito {  Spiciness degree;  public Burrito(Spiciness degree) { this.degree = degree;}  public void describe() {    System.out.print("This burrito is ");    switch(degree) {      case NOT:    System.out.println("not spicy at all.");                   break;      case MILD:      case MEDIUM: System.out.println("a little hot.");                   break;      case HOT:      case FLAMING:      default:     System.out.println("maybe too hot.");    }  }  public static void main(String[] args) {    Burrito      plain = new Burrito(Spiciness.NOT),      greenChile = new Burrito(Spiciness.MEDIUM),      jalapeno = new Burrito(Spiciness.HOT);    plain.describe();    greenChile.describe();    jalapeno.describe();  }} /* Output:This burrito is not spicy at all.This burrito is a little hot.This burrito is maybe too hot.*///:~

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.