撰写一个 myString class,其中包含一个String对象,可于构造函数中通过引数来设定初值。加入toString()和concatenate()。后者会将String对象附加于你的内部字符串尾端。请为myString()实现clone()。撰写两个static函数,令它们都接收myString referencex引数并调用x.concatenate(“test”)。但第二个函数会先调用clone()。请测试这两个函数并展示其不同结果。
我对"撰写两个static函数,令它们都接收myString referencex引数并调用x.concatenate(“test”)。但第二个函数会先调用clone()。"这句不明白,大家能否写下代码让看参考下? 谢谢!

解决方案 »

  1.   


    public class MyString implements Cloneable{

    private String MyString_str;

    public MyString(String str){
    this.MyString_str = str;
    }

    public String concatenate(String str){
    this.MyString_str +=str;
    return this.MyString_str;
    }

    public String toString(){
    return this.MyString_str;
    }

    public Object clone() throws CloneNotSupportedException{
    return super.clone();

    } public static void Method1(MyString MyStr){
    System.out.println(MyStr.concatenate("test"));
    }

    public static void Method2(MyString MyStr){
    try { System.out.println(((MyString) MyStr.clone()).concatenate("test"));
    } catch (CloneNotSupportedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }

    }
    }
    ----------
    import junit.framework.TestCase;
    public class MyStringTest extends TestCase { private MyString m = new MyString(" hello");
    protected void setUp() throws Exception {
    super.setUp();
    } protected void tearDown() throws Exception {
    super.tearDown();
    } public void testMethod() {
    MyString.Method1(m);
    MyString.Method2(m);
    }}
    -----------
    RESULT:
     hellotest
     hellotesttest
      

  2.   

    非常感谢finalzhzhk 热心解答!