Using Static Members

From Wikibooks, open books for an open world
Jump to: navigation, search

Interfaces Java Programming
Using Static Members
Destroying Objects
Navigate Classes and Objects topic: v  d  e )

[edit] What does static mean?

When you declare a

  • method, or
  • member variable

static, it is independent of any particular, but rather it is shared among all instances of a class. To access a static method or member variable, no instance needs to be created.

The static keyword is used to declare a method, or member variable static.

[edit] What can it be used for?

  • Static variables can be used as data sharing amongst objects of the same class. For example to implement a counter that stores the number of objects created at a given time can be defined as so:
Computer code
public AClass
{
   static private int counter;
...
   public AClass()
   {
    ...
      counter += 1;
   }
...
   public int getNumberOfObjectsCreated()
   {
      return counter;
   }
}

The counter variable is incremented each time an object is created.

Public static variable should not be used, as these become GLOBAL variables that can be accessed from everywhere in the program. Global constants can be used, however. See below:

Computer code
static public final String CONSTANT_VAR = "Const";


  • Static methods can be used for utility functions or for functions that do not belong to any particular object. For example:
Computer code
public Match
{
 ...
   public static int addTwoNumbers(int par1, int par2)
   {
        return par1 + par2;
   }
}


[edit] Danger of static variables

Use static variables only for:

  • data sharing (be careful)
  • defining global constants

Use static methods for:

  • utility functions

Using static variables and/or method for other purposes goes against object orientation, which could both be a good and a bad thing.

[edit] External links

Clipboard

To do:
Add some exercises like the ones in Variables

Interfaces Java Programming
Using Static Members
Destroying Objects