簡體   English   中英

創建一個將一個類轉換為另一個類的clone()方法

[英]Creating a clone() method that casts one class to another

我們被要求編寫一個clone()方法,以便執行以下附加代碼:

Circuit c = (Circuit) p2.clone();
System.out.println( c + " = " + c.getResistance());

將產生以下結果:

( ( ( ( 2.0 + 3.0 ) || 4.0) + 1.0 ) || 8.0) = 2.297029702970297

為了簡潔起見,我不會發布所有使用的方法和構造函數(不幸的是,有很多方法和構造函數,因此,如果我要滿足SSCCE提問標准,則將它們全部發布肯定不是簡短明了),但是我將使用這種主要方法向您演示什么是p2

SeriesCircuit s1 = new SeriesCircuit(new Circuit(2.0), new Circuit(3.0));
ParallelCircuit p1 = new ParallelCircuit(s1, new Circuit(4.0));
SeriesCircuit s2 = new SeriesCircuit(p1, new Circuit(1.0));
ParallelCircuit p2 = new ParallelCircuit(s2, new Circuit(8.0));

使用這個:

System.out.println(p2 + " = " + p2.getResistance());

還將打印:

( ( ( ( 2.0 + 3.0 ) || 4.0) + 1.0 ) || 8.0) = 2.297029702970297

PS我已經完成了導致.clone()要求的所有部分。

在分配問問題,我們需要一個轉換SeriesCircuit / ParallelCircuit / CircuitSeriesCircuit / ParallelCircuit / Circuit使用.clone()方法。

每個ParallelCircuitSeries類都包含它們自己的(唯一)私有變量,這些私有變量是通過.getResistance() (返回雙.getResistance()值)或.toString() ,而.toString()獲得的格式化字符串與上面所看到的完全一樣。

有人可以向我解釋如何將具有其私有變量的類轉換為另一個類嗎? 我並不是在要求完整的代碼,盡管我對這個概念有所了解,但我不知道如何執行它。

您需要您的類來實現Cloneable接口。 然后,您可以覆蓋clone()方法。 此方法通過調用super.clone()獲得一個新對象,然后通過為內部函數(和不可變對象)賦值或為對象克隆來復制數據值。 以從類X繼承的類Y為例,

public class X implements Cloneable {

   private int someVariable;

   public X clone() throws CloneNotSupportedException
   {
       X newX=super.clone();
       newX.someVariable=this.someVariable;
       return newX
   }

public class Y extends X implements Cloneable {

   private Z someClassVariable;
   private float myVariable;

   public Y clone() throws CloneNotSupportedException
   {
       Y newY=super.clone();
       newY.someClassVariable=this.someClassVariable.clone();
       newY.myVariable = this.myVariable;

       return newY;
   }


   public class Z implements Cloneable {

   private int someOtherVariable;

   public Z clone() throws CloneNotSupportedException
   {
       Z newZ=super.clone();
       newX.someOtherVariable=this.someVariable;
       return newZ
   }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM