4th: The ability to harden non-instancing through a private constructor

Source: Internet
Author: User

When you need to write a class that contains only static methods and static fields, Like java.lang.math,java.util.arrays, organize the values of the basic type or the related methods on the array type, or, like java.util.Collections, organize static methods on objects that implement a particular interface.

Such a tool class does not want to be instantiated, and the instance has no meaning for it.

An attempt to force a class to be instantiated by making it an abstract class does not work. Because the class can be quilt-like, and subclasses can be instantiated.

We explicitly declare the constructor of the class as private, which is guaranteed to be inaccessible outside of the class.

 Public class Utilityclass {        private  Utilityclass () {            thrownew  Assertionerror ();//Throw an error is not required, but this can guarantee that the class cannot be instantiated inside the class        }}

Such classes are guaranteed not to be quilts, because subclasses always call the superclass constructor explicitly or implicitly in the constructor, and just say that the class's private constructor cannot be accessed outside the class.

4th: The ability to harden non-instancing through a private constructor

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.