Wednesday 2 March 2016

Static Members

A class can contain variables and methods that are shared among all instances of the class. These shared members are called static variables and static methods. The most common use of static variables in a class is to hold predefined constants or unchanging objects that all the instances can use. This approach has two advantages. One advantage is that static values are shared by all instances of the class; the same value can be seen by all instances. More importantly, static members can be accessed even if no instances of the class exist. In this example, we use the static variable Color.red without having to create an instance of the Color class. An instance of the Color class represents a visible color. For convenience, the Color class contains some static, predefined objects with friendly names such as GREEN, RED, and (the happy color) MAGENTA. The variable GREEN, for example, is a static member in the Color class. The data type of the variable GREEN is Color. Internally, in Java-land, it is initialized like this:

 public final static Color GREEN = new Color(0, 255, 0);  
The GREEN variable and the other static members of Color cannot be modified (after they’ve been initialized) so that they are effectively constants and can be optimized as such by the Java VM. The alternative to using these predefined colors is to create a color manually by specifying its red, green, and blue (RGB) components using a Color class constructor.

0 comments:

Post a Comment