Using static and final attributes – An example (II)
6 March 2008Do read Using static and final attributes – An example (I) before going through this post.
Time for an example. I want a limitation on number of object that can be created of my classes called Student.
public class Student { private int id; private String name; private static int counter; private static final int MAXCOUNT=10; public Student(int id, String name) throws Exception { counter++; if(counter > MAXCOUNT) throw new Exception("Limit exceeded. Object not created"); this.id = id; this.name = name; System.out.println("Object created - " + counter); } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public void showAll() { System.out.println("id: " + id); System.out.println("name: " + name); } }
In the constructor, we increment the counter. Also we check if we have reached the upper limit or not. If yes, we throw an exception.
Now lets make sure if this works:
for(int i=0;i<20;i++) { Student obj3 = new Student(i, "name"); }
Output:
Object created - 1 Object created - 2 Object created - 3 Object created - 4 Object created - 5 Object created - 6 Object created - 7 Object created - 8 Object created - 9 Object created - 10 Exception in thread "main" java.lang.Exception: Limit exceeded. Object not created at Student.<init>(Student.java:13) at Test1.main(Test1.java:16)
10 objects were created as shown in the output. When we tried to create 11th object, exception was thrown.
So it works J
Happy coding.
Related Posts:
Top Of Page | Trackback
If you found this page useful, consider linking to it. Simply copy and paste the code below into your web site.
It will look like this: Using static and final attributes – An example (II)
Hello.
I just wanted to say Thank You for all the great tips which you have
shared with us.
Thanks