RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX

By submitting your information, you agree that devx.com may send you DevX offers via email, phone and text message, as well as email offers about other products and services that DevX believes may be of interest to you. DevX will process your information in accordance with the Quinstreet Privacy Policy.

Tip of the Day
Language: Java
Expertise: Intermediate
Dec 4, 2000



Building the Right Environment to Support AI, Machine Learning and Deep Learning

Making Global Objects

Let's take an example: a program has a PrintSpooler class. This class maintains a queue for printer requests and serializes them. The program cannot contain multiple PrintSpooler Objects because this can create unexpected printer output, thus defeating the purpose of having a Spooler class. Global variables are not permitted in Java, but in these types of situations they are needed. A way around this is to use the same object throughout the program. Code can be classed in such a way that it affords the facility of using it like a global object. The following code shows how to do this:
class PrintSpooler {
	static PrintSpooler pr;
	private PrintSpooler(){}; //Don't let anyone create objects directly
	public static PrintSpooler get() //Provide access to the shared 
PrintSpooler object
		if(pr == null)
			pr = new PrintSpooler();
		return pr;
	public void print(String str){/*Print the string*/};
	//Other member functions

Making the constructor private disallows direct object creation. Static function
Nitin Kumar
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date