Using static and final attributes – An example (I)
6 March 2008In this post, I will present an example which used static and final keywords with attributes in meaningful way. I hope after going through this, you will develop good understanding of these.
As may know, that we may access static member of class without using any object of that class. Final field/attribute means that you cannot change its value. If you try to change the value of final attribute, you will get an error – some this like this:
Exception in thread "main" java.lang.Error: Unresolved compilation problem: The final field Student.MAXCOUNT cannot be assigned
Ok – so basics are clear. Not coming to the point. I want to write a class that has some limitations. I want to track the number of object of this class. So a class variable will be there which will be incremented on each object creation. What better place to increment this variable other than constructor. Since, this variable should remain the same for all the instances of the class, therefore we should declare it as static.
I also want an upper limit for the objects. I don’t want more than 10 objects of my class to be created. Static variable again will be a good choice. But since, no one should be allowed to change this from the code, we may declare it as static and final.
Follow the next post for the example.
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 (I)