| 20行目: | 20行目: | ||
result = result * 31 + name.hashCode(); | result = result * 31 + name.hashCode(); | ||
result = result * 31 + hp.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; | return result; | ||
} | } | ||
} | } | ||
2019年6月28日 (金) 20:52時点における版
私は全てのオブジェクトのスーパークラスです。
メソッド
- hashCode - オブジェクトのハッシュ・コード値を知らせる
- toString - オブジェクトの文字列表現を取得する
- clone - オブジェクトのクローンを作成する
- equals - 引数に指定されたオブジェクトと同値かどうか判定する
- wait - 実行中のスレッドを一時待機させる
例
オーバーライドの定石
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;
}
}