How do I restrict object creation not more than 3 in Java class?

We can restrict object creation not more than 3 in Java class by using singleton.it will create single object and share it.

  • Take a class type static variable with private access modifier.
  • Here we will take a static int type variable counter to check how many objects created.
  • Also constructor must be private.
  • We can access static variable inside the constructor and this variable count the number of object created.
  • Write one getInstance getter method.
  • First three time we will create new objects and forth time we need to return 3rd object reference. if we don’t want same object 4th time we can return null.
  • Here first three object have different hash code and fourth, fifth are same hash code.
				
					class Employee {
	private static Employee e;
	public static int objCount = 0;

	private Employee() {
		objCount++;
	}

	public static synchronized Employee getInstance() {
		if (objCount < 3) {
			e = new Employee();
		}

		return e;
	}
}

public class EmployeeObjectCreation {
	public static void main(String[] args) {
		
		Employee e1 = Employee.getInstance();
		Employee e2 = Employee.getInstance();
		Employee e3 = Employee.getInstance();
		Employee e4 = Employee.getInstance();
		Employee e5 = Employee.getInstance();
		
		System.out.println(e1.hashCode());
		System.out.println(e2.hashCode());
		System.out.println(e3.hashCode());
		System.out.println(e4.hashCode());
		System.out.println(e5.hashCode());
	}
}
				
			

Output :-
366712642
1829164700
2018699554
2018699554
2018699554