1. 程式人生 > >java基礎複習(類和物件)

java基礎複習(類和物件)

  • 建構函式(構造器)

1、this() super()都必須是建構函式裡的第一句宣告
若同時出現,那麼原則是:
引數少的構造器用this呼叫引數多的,在引數最多的建構函式裡呼叫 super

  • 靜態變數、靜態方法、常量

static:
被所有的例項共享

final:
不能改變

static variable:
(其實更準確的而講,static 只能作用於field,因為variable是位於方法體內的,而variable不能被宣告為static)

1)It is a variable which belongs to the class and not to object (instance).
2)Static variables are initialized only once, at the start of the execution. These variables will be initialized first, before the initialization of any instance variables.
3)A single copy to be shared by all instances of the class.
A static variable can be accessed directly by the class name and doesn’t need any object.
3)Syntax:Class.variable

static method:
1)It is a method which belongs to the class and not to the object (instance).
靜態方法不能訪問非靜態資料域
2)A static method can access only static data. It can not access non-static data (instance variables) unless it has/creates an instance of the class.
3)A static method can call only other static methods and can not call a non-static method from it unless it has/creates an instance of the class.
4)A static method can be accessed directly by the class name and doesn’t need any object.
5)Syntax:Class.methodName()


6)A static method cannot refer to this or super keywords in anyway.

final static fields:
are global constants

可改變(mutable)與不可改變(immutable)物件
immutable:例如String
mutable:例如Date

不可改變需滿足以下條件:
所有資料域都是私有的
沒有對資料域提供公共的set方法
沒有一個方法會返回一個指向可變資料域的引用

對於最後一點“沒有一個方法會返回一個指向可變資料域的引用”
舉例:

public final
class Period { private final Date start; private final Date end; /** * @param start the beginning of the period. * @param end the end of the period; must not precede start. * @throws IllegalArgumentException if start is after end. * @throws NullPointerException if start or end is null. */ public Period(Date start, Date end) { if (start.compareTo(end) > 0) throw new IllegalArgumentException(start + " after " + end); this.start = start; this.end = end; } public Date start() { return start; } public Date end() { return end; } ... // Remainder omitted }

乍一眼看覺得很正常
接下來:

// Attack the internals of a Period instance
Date start = new Date();
Date end = new Date();
Period p = new Period(start, end);
end.setYear(78);  // Modifies internals of p!

於是,應該做出相應的防禦措施

// Repaired constructor - makes defensive copies of parameters
public Period(Date start, Date end) {
    this.start = new Date(start.getTime());
    this.end   = new Date(end.getTime());

    if (this.start.compareTo(this.end) > 0)
      throw new IllegalArgumentException(start +" after "+ end);
}

但是,做了上述修改後,還會有漏洞:

// Second attack on the internals of a Period instance
Date start = new Date();
Date end = new Date();
Period p = new Period(start, end);
p.end().setYear(78);  // Modifies internals of p!

進一步修改:


//Repaired accessors - make defensive copies of internal fields
public Date start() {
    return (Date) start.clone();
}

public Date end() {
    return (Date) end.clone();
}

以上參考此網址