Do not know whether the friends have thought, in the implementation of a class, you can make this class only one object. Only one object class is not very interesting ~
Simple idea:
To think of only one object, so consider, first of all, this class can not have the user directly create the object of the construction method, should let the class implementation control the creation of objects, here to think about, if you want to create a class object when the user does not have to create a class object, You should consider using static object Members here. After the static object is used, then the static method is used to initialize the static object member.
/**
* Implements a class that has only one object
* @author: Wolfofsiberian */
public
class onlyoneobject{
private String Name =null;
private static Onlyoneobject Oneobject = new Onlyoneobject ();
Private Onlyoneobject () {
name= "one object";
System.out.println ("Invoke Private constructor:" +name);
}
public static Onlyoneobject Makeonlyoneobject () {return
oneobject;
}
public void SetName (String name) {
This.name=name
}
Public String GetName () {return
name;
}
For test public
static void Main (string[] args) {
onlyoneobject oneobject=onlyoneobject.makeonlyoneobject ();
System.out.println ("GetName ():" +oneobject.getname ());
Oneobject.setname ("wolfofsiberian!");
System.out.println ("SetName ():" +oneobject.getname ());
}
}
Run Result:
F:\01 java\01 project\01 tinkinginjava>java onlyoneobject
Invoke Private Constructor:one Object
GetName () : one object
SetName (): wolfofsiberian!