(java.lang.)Object [1]

私は全てのオブジェクトのスーパークラスです。

メソッド

  • 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;
    }   
}