看了thinking in java 的initialize and cleanup 的一点总结

来源:互联网 发布:游戏常用算法 编辑:程序博客网 时间:2024/05/17 05:02

关于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 peelreturn 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 };


0 0
原创粉丝点击