看了thinking in java 的initialize and cleanup 的一點總結

關於this:

1 Can only be used in the non-static method-produce the reference to the object the method has been called for.

2 it's often used in the return statement when you want to return the reference to the current object.

3 multiple object can be easily performed on the same object 

4 passing the current object to another method.Within the inner class itself, you can use OuterClass.this.

Get the outer class from the inner clas.

I don't think there's a way to get the instance from outside the code of the inner class though. Of course, you can always introduce your own property:

public OuterClass getOuter() {
return OuterClass.this;
}

class Person {
public void eat(Apple apple) {
Apple peeled = apple.getPeeled();
System.out.println("Yummy");
}
}
class Peeler {
static Apple peel(Apple apple) {
// ... remove peel
return apple; // Peeled
}
}
class Apple {
Apple getPeeled() { return Peeler.peel(this); }
}
public class PassingThis {
public static void main(String[] args) {
new Person().eat(new Apple());
}
}

上面的例子中, Peeler,peel() is as a utility method, and can pass the current object to the peeler.

(Let the apple worry about how to peel itself.)

5 Calling constructor from constructor

When this is used, can't call two, and the constructor call must be the first thing to do.



關於cleanup:

1 What to collect?

The garbage collector only knows how to collect memory allocated with new. So it doesn't know how to release special memory. To handle this , you can use the method finalize() that you can define for your class. 


2 How to collect?

When the garbage collector is ready to release the storage used for your object, it will first call finalize(), and only on next garbage- collection pass will it reclaim the object's memory. So it gives you the ability to perform some important cleanup at the time of garbage collection.


3 When it is called?

You can't rely on the method to be called. You can use the method to finally check some properties of the object (it will execute at some point).


關於static initialization 和 non-static initialization 一種語法:

static {

}

{

}


關於Array Initialization:

1 array initialization happens at run time

2 Integer[] b = new Integer[]{
new Integer(1),
new Integer(2),
3, // Autoboxing
};


int[] a1 = { 1, 2, 3, 4, 5 };


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章