"Java" "Tij" Builds a class: This class has only one object (instance) __java

Source: Internet
Author: User


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!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.