We already know that if two objects of a class have the same reference, then they have the same entities and functions, such as:
Aone=newA();Atwo=one;
Assume that class A has an int member variable named x. Then, if you perform the following operations:
two.x=100;
Then the value of one.x will also be 100.
For another example, the parameter of a certain method is of type People:
publicvoidf(Peoplep){px=200;}
If when calling this method, a reference to an object of People, such as zhang, is passed to parameter P, then the value of zhang.x will also be 200 after the method is executed.
Sometimes you want to get a "copy" of an object. Changes in the copy entity will not cause changes in the original object entity, and vice versa. Such a copy is called a clone object of the original object or simply a clone .
It is easy to obtain a clone of a serialized object using object streams. Simply write the object to the destination pointed by the object output stream, and then use that destination as the source of an object input stream, which then reads from the source. The object returned must be a clone of the original object, that is, the object input stream obtains a clone of the current object through the serialization information of the object. For example, the object xinfei in the example in the previous section is a clone of the object changhong.
When a program wants to get a clone of an object faster, it can use an object stream to write the serialization information of the object into memory instead of writing it to a file on disk. Object stream uses array stream as the underlying stream to write the serialization information of the object into memory. For example, we can take the example in the previous section
FileOutputStreamfileOut=newFileOutputStream(file);ObjectOutputStreamobjectOut=newObjectOutputStream(fileOut);
and
FileInputStreamfileIn=newFileInputStream(file);ObjectInputStreamobjectIn=newObjectInputStream(fileIn);
Change to:
ByteArrayOutputStreamoutByte=newByteArrayOutputStream();ObjectOutputStreamobjectOut=newObjectOutputStream(outByte);
and
ByteArrayInputStreaminByte=newByteArrayInputStream(outByte.toByteArray());ObjectInputStreamobjectIn=newObjectInputStream(inByte);
The Component class in the java.awt package is a class that implements the Serializable interface. The component is a serialized object . Therefore, the program can write the component to the output stream, and then use the input stream to read a clone of the component.