11 JAVA的匿名對消

Person

public class Person {
    String name; // 成員變量默認的修飾符是default,只能在當前類或者同一個包中訪問

    public void showName() {
        System.out.println("我是" + this.name);
    }
}

Demo01Anonymous

/**
 * 匿名對象
 * 普通標準格式
 * 類名稱 變量 = new 類();
 *
 * 匿名:new 類()
 * 注意事項,每一次都是新建的對象,所以一般在只需要使用一次的場合下使用
 */
public class Demo01Anonymous {
    public static void main(String[] args) {
        // 普通
        Person one = new Person();
        one.name = "楊冪";
        one.showName();

        // 匿名
        new Person().name = "范冰冰";
        new Person().showName(); // null,因爲冰冰已經涼了

    }

}

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