public class dog{public
Dog () {
super ();
}
}
1, the creation of objects what is difficult, we are new one is .... ...... Yes, that's right, it's just one of them.
Dog jack = new Dog ();
2, using the reflection mechanism of class, this kind of method is suitable for the
Class dogclass = Dog.class; Get class Dog class instance Object
Dog Rose = (Dog) dogclass.newinstance ();//Call instance method of Class newinstance () Create instance object of Dog
Class Dogclass = Class.forName ("Dog");
Dog rose = (Dog) dogclass.newinstance ();
3, the use of Java objects, serializable (object in memory distribution way, in the local preservation of an identical look, and then removed to use, the equivalent of an object of the state of a completely saved, very good ah, is not a game often so do), Use the Encapsulation class: Objectoutputstream,objectinputstream.
Prerequisite: This class must implement interface serializable
public class Createfour implements Serializable {public
static void Main (String args[]) {
Createfour fcreatefour = new Createfour ();
ObjectOutputStream Objectstream;
try {
objectstream = new ObjectOutputStream (New FileOutputStream ("Res/obj.txt"));
Objectstream.writeobject (fcreatefour);
ObjectInputStream ObjectInputStream = new ObjectInputStream (New FileInputStream ("Res/obj.txt"));
Createfour Clonefour = (createfour) objectinputstream.readobject ();
} catch (FileNotFoundException e) {
//TODO auto-generated catch block
e.printstacktrace ();
} catch ( IOException e) {
//TODO auto-generated catch block
e.printstacktrace ();
} catch ( ClassNotFoundException e) {
//TODO auto-generated catch block
e.printstacktrace ();
}
}
}
4, using the object instance method clone (), the class must implement the Cloneable interface, or it will throw an exception clonenotsupportedexception
public class Createfour implements cloneable {public
static void Main (String args[]) {
Createfour f = new Createf Our ();
try {
Createfour cloneobject = (createfour) f.clone (),
catch (Clonenotsupportedexception e) {
//TODO auto- Generated catch block
e.printstacktrace ();}}
5, summary
A: OK, 4 ways to create an object, and the partners know ..... Using object flow, or clone (), will open up new memory space in which the heap memory in the JVM replicates a new object that is the same as the source object (never assume that the old reference corresponds to the same object as the new reference)