Java Program Example How to Restrict a class to crate only 5 objects in Java.

Sanjay Singh
2 min readSep 17, 2019

--

Question: How to restrict a class from creating multiple objects?

We know by using singleton we can restrict a class to creating multiple objects.But in singleton design pattern can create only one object .So we can use singleton design pattern with some changes please follow the step

Step 1 — Take a class type static variable

private static RestrictObject object;

Step 2 — declare one static int type variable for count (for object creation count)

private static int count;

Step 3 — constructor must be private

private RestrictObject() {

/*every object creation count must be increase by 1*/

System.out.println(“Object created count =” + count);

count++;

}

Step 4 — write one getter method

public static RestrictObject getObject() {

if (count < 6) {

object = new RestrictObject();

}

return object;

}

=================================

package com.blog.example;

public class RestrictObject {

private static RestrictObject object;

private static int count;

private RestrictObject() {

/*every object creation count must be incress by 1*/

count++;

}

public static RestrictObject getObject() {

if (count < 6) {

object = new RestrictObject();

}

return object;

}

}

=======

package com.blog.example;

public class ExampleTesting {

public static void main(String[] args) {

RestrictObject obj1 = RestrictObject.getObject();

RestrictObject obj2 = RestrictObject.getObject();

RestrictObject obj3 = RestrictObject.getObject();

RestrictObject obj4 = RestrictObject.getObject();

RestrictObject obj5 = RestrictObject.getObject();

RestrictObject obj6 = RestrictObject.getObject();

RestrictObject obj7 = RestrictObject.getObject();

RestrictObject obj8 = RestrictObject.getObject();

RestrictObject obj9 = RestrictObject.getObject();

RestrictObject obj10 = RestrictObject.getObject();

System.out.println(obj1.hashCode());

System.out.println(obj2.hashCode());

System.out.println(obj3.hashCode());

System.out.println(obj4.hashCode());

System.out.println(obj5.hashCode());

System.out.println(obj6.hashCode());

System.out.println(obj7.hashCode());

System.out.println(obj8.hashCode());

System.out.println(obj9.hashCode());

System.out.println(obj10.hashCode());

}

}

=====

output

Object created count =0

Object created count =1

Object created count =2

Object created count =3

Object created count =4

Object created count =5

2018699554

1311053135

118352462

1550089733

865113938

1442407170

1442407170

1442407170

1442407170

1442407170

if object has been same , then hash code must be same

--

--

Sanjay Singh
Sanjay Singh

Written by Sanjay Singh

Java, Spring Boot & Microservices developer Sharing knowledge, tutorials & coding tips on my Medium page. Follow me for insights & see story list section

Responses (1)