社内se × プログラマ × ビッグデータ

プログラミングなどITに興味があります。

Java challenge cloneable

Java challenge 既出のコードです。
出力結果を考えてみます。

ソースコード
public class CloneableChallenge {
    public static void main(String[] args) throws CloneNotSupportedException {
        Human human17 = new Human("cells");
	Human human18 = (Human) human17.clone();
		
	System.out.println(human17.equals(human18));
    }
	
    static class Human implements Cloneable {
	Cell cell;
		
	public Human(String cellName) {
	    this.cell = new Cell(cellName);
	}
		
	@Override
	public Object clone() throws CloneNotSupportedException {
	    return super.clone();
	}
    }
	
    static class Cell {
	String name;
	public Cell(String cellName) {
	    name = cellName;
        }
    }
}
予想

"false" が出力される。
正直、Cloneable をちゃんと使ったことがないので、clone 自体のコードに問題があるか分からないです。
単純に Human クラスのインスタンスが正常に clone 出来たと仮定したら、 それぞれ別のメモリ上に存在するはず。

結果

"false" が出力された。
うーん。ただ、上記の理解で正しいのかが分からない。
実際にこの challenge をした人のコメントを見てみると、human17.cell.equals(human18.cell) では true が返ってくるらしい(手元の環境でも true になった)。

Human class は別々のオブジェクトだが、クラス変数である Cell は同じオブジェクトを参照しているということか。

以下のサイトも参考になりました。
promamo.com

試したソースコード
github.com