「Java」clone()メソッドでオブジェクトをコピーするサンプル

書式
public Object clone() throws CloneNotSupportedException {
return super.clone();
}
使用例
親クラス

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
package com.arkgame.study.javlesson;
public class BaseSample implements Cloneable {
private String username;
//コンストラクター
public BaseSample(String str) {
this.username = str;
}
// toStrメソッドの定義
public String toStr() {
return username + "**222";
}
//cloneメソッド
public Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
package com.arkgame.study.javlesson; public class BaseSample implements Cloneable { private String username; //コンストラクター public BaseSample(String str) { this.username = str; } // toStrメソッドの定義 public String toStr() { return username + "**222"; } //cloneメソッド public Object clone() throws CloneNotSupportedException { return super.clone(); } }
package com.arkgame.study.javlesson;

public class BaseSample implements Cloneable {
      private String username;

      //コンストラクター
      public BaseSample(String str) {
            this.username = str;
      }
      // toStrメソッドの定義
      public String toStr() {
            return username + "**222";
      }
      //cloneメソッド
      public Object clone() throws CloneNotSupportedException {
            return super.clone();
      }

}

動作確認クラス

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
package com.arkgame.study.javlesson;
public class CloneTest {
public static void main(String[] args) throws CloneNotSupportedException {
// オブジェクトbs1
BaseSample bs1 = new BaseSample("user_object_test");
System.out.println("結果1:\n" + bs1.toStr());
//オブジェクトbs2
BaseSample bs2 = (BaseSample) bs1.clone();
System.out.println("オブジェクトのコピー結果2:\n" + bs2.toStr());
}
}
package com.arkgame.study.javlesson; public class CloneTest { public static void main(String[] args) throws CloneNotSupportedException { // オブジェクトbs1 BaseSample bs1 = new BaseSample("user_object_test"); System.out.println("結果1:\n" + bs1.toStr()); //オブジェクトbs2 BaseSample bs2 = (BaseSample) bs1.clone(); System.out.println("オブジェクトのコピー結果2:\n" + bs2.toStr()); } }
package com.arkgame.study.javlesson;

public class CloneTest {

      public static void main(String[] args) throws CloneNotSupportedException {
           // オブジェクトbs1
            BaseSample bs1 = new BaseSample("user_object_test");
            System.out.println("結果1:\n" + bs1.toStr());
            
            //オブジェクトbs2
            BaseSample bs2 = (BaseSample) bs1.clone();
            System.out.println("オブジェクトのコピー結果2:\n" + bs2.toStr());

      }

}

実行結果
結果1:
user_object_test**222
オブジェクトのコピー結果2:
user_object_test**222

Java

Posted by arkgame