Java learning notes-12. Passing and returning objects, learning notes-12
1. The Clone () method generates an object. After the method is used, the value of the object must be assigned.
Vector v2 = (Vector)v.clone();
2. the Clone () method is a protection type method in the object. If you need to use the Clone () method to create a class, you need to write it again and inherit the Cloneable interface.
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. to clone a class, perform the following steps: (1) Implement the Cloneable interface.
(2) overwrite the Clone () method
(3) Call super. Clone () in your own clone () method ()
(4) capture the violation in your own clone ()
4. all the methods that can modify the String in the String class are created and a new String class is returned. The original String class is not changed, including ++ and ++ =, stringBuffer is more effective than String operations.
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); }}