Static class members
Static class member methods and variables can be static properties, according to a statement static members static modifier.
A key cycle class design is to decide whether a method or variable is declared as static.
Static variables
Any variable or code is compiled, the program automatically assigned by the system memory to memory, and the so-called static refers After compiling the allocated memory will always exist, it will free up memory space until the program is launched.
In java program, everything is an object, and the object is abstract class, for a class, if you want to use members of his (refer to members of the class of functions, variables)
Static method
Static method is to use a common memory space, that all objects can be referenced directly, do not need to re-create objects using this method.
Static methods can be invoked through the class name, and therefore does not have to call the static method is instantiated.
1 public class SloganCounter
2 {
3 // number Slogan create several objects and create print objects.
. 4 public static void main (String [] args)
. 5 { // create a custom banner objects
. 6 Slogan obj;
. 7 // create and populate obj, and in the print object character string
. 8 obj = new new Slogan ( "Remember The Alamo. " );
. 9 System.out.println (obj);
10
. 11 obj = new new Slogan (" Happy the Do Not Worry of Be. ". );
12 is System.out.println (obj);
13 is
14 = obj new new Slogan ( "Live as Free or Die." );
15 System.out.println (obj);
16
. 17 obj = new new Slogan ( "Cheap Talk IS." );
18 is System.out.println (obj);
. 19
20 is obj = new new Slogan ( "the Write Once, the Run Anywhere." );
21 is System.out.println (obj);
22 is
23 is System.out.println ();
24 // getCount () to obtain a sequence number
25 // output the number of objects in the slogan
26 is System.out.println ( "slogans Created:" + Slogan.getCount ());
27 }
28 }
. 1 public class Slogan
2 {
. 3 Private String phrase;
. 4 Private static int COUNT = 0 ;
. 5
. 6 // --------------------------- --------------------------------------
7 // constructor: calculate the number of instances and disposed banners create.
8 // ----------------------------------------------- ------------------
. 9 public Slogan (String STR)
10
. 11 phrase = STR;
12 is COUNT ++ ;
13 is }
14
15 //-----------------------------------------------------------------
16 // 将此口号作为字符串返回。
17 //-----------------------------------------------------------------
18 public String toString()
19 {
20 return phrase;
21 }
22
23 //-----------------------------------------------------------------
24 // 返回此类的实例数创建
25 //-----------------------------------------------------------------
26 public static int getCount()
27 {
28 return count;
29 }
30 }
Slogan类的getCount方法也声明为静态类的,允许在main方法中通过类名调用该方法。
在getCount方法中被应用的唯一数据是整形静态变量count。作为静态方法,getCount不能引用任何其他非静态变量。