Java學習筆記-12.傳遞和返回對象,學習筆記-12

來源:互聯網
上載者:User

Java學習筆記-12.傳遞和返回對象,學習筆記-12

1.Clone()方法產生一個object,使用方法後必須產生的object賦值。

Vector v2 = (Vector)v.clone();

2.Clone()方法在object中是保護類型方法,如果自己建立的類需要使用Clone()方法的話需要自己重新寫一個,並且繼承Cloneable介面。

package tweleve;import java.util.*;class MyObject implements Cloneable {    int i;    MyObject(int ii) {        i = ii;    }    public Object clone() {        Object object = null;        try {            object = super.clone();        } catch (CloneNotSupportedException e) {            System.out.println("MyObject can't clone");        }        return object;    }    public String toString() {        return Integer.toString(i);    }}public class LocalCopy {    static MyObject g(MyObject v) {        v.i++;        return v;    }    static MyObject f(MyObject v) {        v = (MyObject) v.clone();        v.i++;        return v;    }    public static void main(String[] args) {        MyObject aMyObject = new MyObject(11);        MyObject bMyObject = g(aMyObject);        if (aMyObject == bMyObject)            System.out.println("a==b");        else            System.out.println("a!=b");        System.out.println("a=" + aMyObject);        System.out.println("b=" + bMyObject);        MyObject cMyObject = new MyObject(31);        MyObject dMyObject = f(cMyObject);        if (cMyObject == dMyObject)            System.out.println("c==d");        else            System.out.println("c!=d");        System.out.println("c=" + cMyObject);        System.out.println("d=" + dMyObject);    }}

3.如果希望一個類能夠複製那麼需要有下列步驟:(1)實現Cloneable介面

                                                                             (2)覆蓋Clone()方法

                                                                             (3)在自己的Clone()方法中調用super.clone()

                                                                             (4)在自己的clone()中捕獲違例 

4.String類中所有能修改String的方法其實都建立和返回了一個新的String類,原來的String類是沒有改變的,包括+和+=,StringBuffer比String操作字串時更有效。

package tweleve;import java.sql.Ref;import org.omg.CORBA.SystemException;public class Stringer {    static String upcase(String s){         return s.toUpperCase();    }        public static void main(String[] args){        String qString=new String("howdy");        System.out.println(qString);        String qq=upcase(qString);        System.out.println(qq);        System.out.println(qString);    }}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.