私は全てのオブジェクトのスーパークラスです。
メソッド
- hashCode - オブジェクトのハッシュ・コード値を知らせる
- toString - オブジェクトの文字列表現を取得する
- clone - オブジェクトのクローンを作成する
- equals - 引数に指定されたオブジェクトが同じか真偽する
- wait - 実行中のスレッドを一時待機させる
例
hashCodeオーバーライドの定石
class Hero {
String name;
int hp;
public int hashCode() {
int result = 37;
result = result * 31 + name.hashCode();
result = result * 31 + hp.hashCode();
return result;
}
}
clone実装の例
Object自身はインタフェースCloneableを実装していないため、クラスで実装する必要があります。
public class Hero implements Clonable {
String name;
int hp;
Sword sword;
public Hero clone() {
Hero result = new Hero();
result.name = this.name;
result.hp = this.hp;
result.sword = this.sword; // shallow copy
// result.sword = this.sword.clone(); // deep copy
return result;
}
}
equalsオーバーライドの定石
public boolean equals(Object o) {
if (o == this) return true;
if (o == null) return false;
if(!(o instanceof Account)) return false;
Account r = (Account) o;
if (!this.accountNo.trim().equals(r.accountNo.trim())) {
return false;
}
return true;
}