Statics

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • rengaraj
    New Member
    • Jan 2007
    • 168

    #1

    Statics

    Can anyone help ?

    1)where we need to use static methods & static variable in a real time projects?

    2)How to Count total numbers of object created by that class in java by using static variable's ?
  • r035198x
    MVP
    • Sep 2006
    • 13225

    #2
    Originally posted by rengaraj
    Can anyone help ?

    1)where we need to use static methods & static variable in a real time projects?

    2)How to Count total numbers of object created by that class in java by using static variable's ?
    Static variables are shared among objects of the same class.
    If you have a class called MyClass with a static variable called myVariable, then there's only ever one copy of myVariable no matter how many objects you create of type MyClass. So all MyClass type objects share the same myVariable.
    To count how many instances of a class are created, you need to have a static variable in that class and increment its value everytime a new object is created from that class. A possible place to put the code for the incrementing is in an instance initializer block.

    Comment

    • BigDaddyLH
      Recognized Expert Top Contributor
      • Dec 2007
      • 1216

      #3
      Newbies tend to write too many static members. As a rule of thumb I suggest:
      1. Start with only one static method, your main (if your code requires a main). Try to keep your main as short as possible -- a long main encourages you to define other static members.
      2. Start with "constants" as your only static fields:
        [CODE=Java]public static final long MY_CONSTANT = 1;[/CODE]
      3. What other fields must be static? It shouldn't be because it's convenient to do so, but because it's logically wrong not to! The example of counting the number of instances generated of a class is one example, but it is a contrived one -- I can't imagine needing to do that in a real application.
      4. What other methods must be static? Simple utility methods are a candidate. See javax.swing.Swi ngUtilities, for example.
      5. The Singleton Pattern is an example requiring static members, but it's also the most overused/abused design pattern. Again use it because it's logically wrong not to, not because it's easy to do.

      Comment

      Working...