Think in java 學習筆記:初始化與清理

1.用構造器確保初始化

  • 以下為帶有構造器的簡單類
    class Rock{ Rock(){ System.out.println("Rock"); } } public class Test{ public static void main(String[] args){ Rock r = new Rock(); } }
    在創建對象時,new Rock()將會為對象分配內存,并調相應的構造器。不接受任何參數的構造器是默認構造器。構造器也可以帶參數,以便于指定如何創建對象。
  • 對默認構造器,如果你已經創建了一個構造器(無論是否有參數),編譯器就不會為你自動創建默認構造器。例如
    class Bird2{ Bird2 int }

2. this 關鍵字

  • this關鍵字表示對“調用方法的那個對象”的引用。例如
    class Leaf{ int i = 0; Leaf increment(){ i++; return this; } void print(){ System.out.println(i); } public static void main(String [] args){ Leaf l = new Leaf(); l.increment().increment().increment().print(); } }

  • this關鍵字將當前對象傳遞給其他方法。
    class Person{ public void eat(Apple apple){ Apple peeled = apple.getPeeled(); System.out.println("Yummy"); } } class Apple{ Apple getPeeled() { return Peeler.peel(this); } } class Peeler{ static Apple peel(Apple apple){ return apple; } } public class PassingThis { public static void main(String[] args) { new Person().eat(new Apple()); } }
    Apple需要調用Peeler.peel()方法,它是一個外部的工具方法,將執行由于某種原因必須放在Apple外部的操作(可能是因為該外部方法要應用于不同的類,而卻不想重復這段代碼)。為了將其自身傳遞給外部方法,Apple必須使用this關鍵字。

  • 在構造器中調用構造器
    public class Flower { int petalCount = 0; String s = "initial value"; Flower(int petals) { petalCount = petals; System.out.println(petalCount); } Flower(String ss){ s = ss; System.out.println(s); } Flower(int petals,String s){ this(petals); //this(s); this.s = s; System.out.println("String & int args"); } Flower() { this(5,"hi"); } void printPetalCount(){ //this(); System.out.println(petalCount+" "+ s); } public static void main(String[] args) { Flower f = new Flower(); f.printPetalCount(); } }
    可以用this調用一個構造器,不能調用兩個,另外,必須將構造器調用置于最起始處。除構造器外,編譯器禁止其他任何方法中調用構造器。當參數和數據成員名字相同時可以用this區分。

3.static

  • static方法就是沒有this的方法。static方法中不能調用非靜態方法,反過來可以。可以在沒有創建任何對象的情況下 ,通過類本身來調用static方法。它很像全局方法,java中禁止全局方法。

4.清理

java的垃圾回收器;finalize()方法。
無論是垃圾回收還是終結,都不保證一定會發生。如果java虛擬機(JVM)并未面臨內存耗盡的情況,它是不會浪費時間去執行垃圾回收以恢復內存的。

5. 初始化順序

在類的內部,即使變量定義散布于方法定義之間,它們仍然會在任何方法被調用之前得到初始化。

package com.zhangyue.learn;


class Window{
    public Window(int maker) {
        System.out.println("window"+maker);
    }
}

class House{
    public House() {
        System.out.println("House");
        w3 = new Window(1);
    }
    Window w2 = new Window(2);
    public void f(){
        System.out.println("f()");
    }
    Window w3 =  new Window(3);
}

public class OrderOfInitialization {

    public static void main(String[] args) {
        House h = new House();
        h.f();
    }

}
/* output
window2
House
window1
f()
*/

6. 靜態數據的初始化

package com.zhangyue.learn;


class Bowl{
    public Bowl(int marker) {
        System.out.println("Bowl"+marker);
    }
    void f1(int marker){
        System.out.println("f1"+marker);
    }
}

class Table{
    static Bowl b1 = new Bowl(1);
    public Table() {
        System.out.println("Table");
        b2.f1(1);
    }
    void f2(int marker){
        System.out.println("f2"+marker);
    }
    static Bowl b2 = new Bowl(2);
}

class Cupboard{
    Bowl b3 = new Bowl(3);
    static Bowl b4 = new Bowl(4);
    public Cupboard() {
        System.out.println("Cupboard");
        b4.f1(2);
    }
    void f3(int marker){
        System.out.println("f3"+marker);
    }
    static Bowl b5 = new Bowl(5);
}

public class StaticOrderOfInitialization {

    public static void main(String[] args) {
        System.out.println(1);
        new Cupboard();
        System.out.println(2);
        new Cupboard();
        t.f2(1);
//      c.f3(1);
    }
    static Table t = new Table();
//  static Cupboard c = new Cupboard();

/*Bowl1
Bowl2
Table
f11
1
Bowl4
Bowl5
Bowl3
Cupboard
f12
2
Bowl3
Cupboard
f12
f21
*/

}

靜態對象初始化過之后就不會再被初始化了,從第一個Cupboard和第二個Cupboard對象的初始化比較可看出。
初始化的順序是先靜態對象,后非靜態對象。

7. 數組的初始化

package com.zhangyue.learn;

public class DynamicArray {

    public static void main(String[] args) {
        Other.main(new String[]{"a","b","c"});
    }

}

class Other{
    static void main(String[] args){
        for (String s : args) {
            System.out.print(s+" ");
        }
    }
}

8. 可變參數列表

public class DynamicArray {
    public static void printArray(Object ... c){
        for (Object a : c) {
            System.out.print(a);
        }
    }
    public static void main(String[] args) {
        printArray(1,2,3);
    }
}

9. 枚舉類型

public enum Spiciness {
    NOT,MILD,MEDIUM,HOT,FLAMING
}

創建enum時,編譯器會自動添加一些有用的特性,如toString(),以便于方便顯示實例內容,還有ordinal(),表示順序,還有static values(),按順序構成數組。
與switch連用顯示了它的特性

package com.zhangyue.learn;


public class SimpleEnumUse{
    Spiciness degree;
    public SimpleEnumUse(Spiciness degree){
        this.degree = degree;
    }
    public void describe(){
        System.out.println("aaaa");
        switch(degree){
        case NOT:System.out.println(1);break;
        case MILD:System.out.println(2);break;
        case MEDIUM:System.out.println(3);break;
        case HOT:System.out.println(4);break;
        case FLAMING:System.out.println(5);break;
        default : System.out.println(0);
        }
    }
    public static void main(String[] args){
        SimpleEnumUse 
        s = new SimpleEnumUse(Spiciness.NOT),
        m = new SimpleEnumUse(Spiciness.FLAMING),
        n = new SimpleEnumUse(Spiciness.HOT);
        s.describe();
        m.describe();
        n.describe();
        
    }
}
/*aaaa
1
aaaa
5
aaaa
4
*/

10. 引用的初始化

編譯器不是為每個引用都創建默認對象,如果想初始化這些引用有下面幾種方法

package com.zhangyue.learn;

class Soap{
     private String s;
     //構造器初始化
     Soap() {
        System.out.println("Soap()");
        s = "Constructed";
    }
     public String toString(){
         return s;
     }
}
public class YinYongInitialization {
    //在定義的位置初始化
    private String
    s1 = "Happy",
    s2 = "Happy",
    s3,s4;
    private int i;
    private Soap castille;
    private float toy;
    public YinYongInitialization(){
        System.out.println("Inside class");
        s3 = "Joy";
        toy = 3.14f;
        castille = new Soap();
    }
    //使用實例初始化
    {i = 47;}
    public String toString(){
        //在正要使用對象之前初始化,即惰性初始化
        if (s4 == null) {
            s4 = "Joy";
        }
        return s1+s2+s3+s4+toy+i+castille;
    }
    public static void main(String[] args) {
        YinYongInitialization y = new YinYongInitialization();
        System.out.println(y);
    }

}

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 230,247評論 6 543
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 99,520評論 3 429
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 178,362評論 0 383
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 63,805評論 1 317
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 72,541評論 6 412
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 55,896評論 1 328
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,887評論 3 447
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 43,062評論 0 290
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 49,608評論 1 336
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 41,356評論 3 358
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 43,555評論 1 374
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 39,077評論 5 364
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 44,769評論 3 349
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 35,175評論 0 28
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 36,489評論 1 295
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 52,289評論 3 400
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 48,516評論 2 379

推薦閱讀更多精彩內容

  • 1. Java基礎部分 基礎部分的順序:基本語法,類相關的語法,內部類的語法,繼承相關的語法,異常的語法,線程的語...
    子非魚_t_閱讀 31,736評論 18 399
  • Spring Cloud為開發人員提供了快速構建分布式系統中一些常見模式的工具(例如配置管理,服務發現,斷路器,智...
    卡卡羅2017閱讀 134,826評論 18 139
  • SwiftDay011.MySwiftimport UIKitprintln("Hello Swift!")var...
    smile麗語閱讀 3,854評論 0 6
  • 多態 任何域的訪問操作都將有編譯器解析,如果某個方法是靜態的,它的行為就不具有多態性 java默認對象的銷毀順序與...
    yueyue_projects閱讀 971評論 0 1
  • 剛做完頭療回來,整個人感覺輕松多了。 我一天沒出現,那是因為我頭痛,頭痛是我自找的,也怨不了誰睡。 跟朋友說:“我...
    留不住的擱淺閱讀 570評論 4 7