The creation of a class that can have only one instance in Java

Source: Internet
Author: User

In Java, if we create a class that wants the class to have only one object, then we can

1: Design The construction method of this class as private

2: Define a static method in the class that creates the object in the method

 Packagetest;/** Sometimes we want a class to have only one instance at any given time, so we can design this class as a singleton pattern. * To design a class as a singleton mode, you need: * 1: The access modifier for the constructor method of the class is private * 2: Then define a static method in the class that creates the object of the class in the method **/ Public classSingleton {Private Static FinalSingleton INSTANCE =NewSingleton ();//Private Members    Private intA = 0;//Private Members            PrivateSingleton () {}//Construction Method     Public Static synchronizedSingleton getinstance () {//methods of the class        returnINSTANCE; }     Public voidMethodA () {//member Methodsa++; System.out.println ("A =" +a); }     Public Static voidMain (string[] args) {//Main MethodSingleton SG1 =singleton.getinstance (); Singleton SG2=singleton.getinstance ();        Sg1.methoda ();        Sg2.methoda (); System.out.println (SG1==SG2); }}

The creation of a class that can have only one instance in Java

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.