Java program to create upto 3 object for a class and throw Userdefined Exception if trying to create 4th one


ObjectCreation.java

package com.nt.object; public class ObjectCreation{ private static int count=0; private ObjectCreation() { count++; } public static ObjectCreation getInstance() { if(count<3) return new ObjectCreation(); else throw new ObjectCreationOutOfBoundException("Can't create more than three objects!!!"); } }

ObjectCreationOutOfBoundException.java

package com.nt.object; public class ObjectCreationOutOfBoundException extends RuntimeException { public ObjectCreationOutOfBoundException(String s) { super(s); } }

Test.java

package com.nt.object; public class Test { public static void main(String[] args) { ObjectCreation obj1=ObjectCreation.getInstance(); System.out.println("Created first object : "+obj1); ObjectCreation obj2=ObjectCreation.getInstance(); System.out.println("Created second object : "+obj2); ObjectCreation obj3=ObjectCreation.getInstance(); System.out.println("Created third object : "+obj3); //here exception will generate ObjectCreation obj4=ObjectCreation.getInstance(); } }
Share:

No comments:

Post a Comment

Quote of the day

Popular Posts

Featured Post

Collection Framework Overview

Collection:- A collection (sometimes called a container) is simply an object that groups multiple elements into single unit. Collect...

Youtube Page

Facebook Page

Recent Posts

About

I am Shivaji Chandra and I'm a Computer Science Engineer. I love to write poems, jokes and quotes. click here →