StaticDemo.java
01 package ch4;
02 /**
03  * Simple class used to demo static variables and methods
04  */
05 public class StaticDemo {
06   private static int numCreated;
07   private String name;
08 
09   public StaticDemo(String name) {
10     this.name = name;
11     numCreated++;
12   }
13 
14   public static void main(String[] args) {
15     //no instance needed to call a static method
16     printAllStaticInfoAvaliable();
17     
18     StaticDemo staticDemo1=new StaticDemo("demo1");
19     StaticDemo staticDemo2=new StaticDemo("demo2");
20     
21     //instance of Class (StaticDemo) is needed to call non static method
22     //each instance has a diffent name, numCreated is shared by all instances
23     staticDemo1.printAllInfoAvaliable();
24     staticDemo2.printAllInfoAvaliable();
25   }
26 
27   //Non static methods have access to static and non static member variables
28   //name and numCreated can be printed
29   public void printAllInfoAvaliable() {
30     System.out.println("name="+name);
31     System.out.println("numCreated="+numCreated);
32   }
33 
34   //Static methods can only access static class level variables
35   //name can not be printed
36   public static void printAllStaticInfoAvaliable() {
37     System.out.println("numCreated="+numCreated);
38   }
39 
40   //could have been declared static, but there is no need for an instance
41   public static int getNumCreated() {
42     return numCreated;
43   }
44 
45   public String getName() { //can not be declared static
46     return name;
47   }
48 }
49 
50 /**
51  * Used to demo a class calling another's static variables and methods.
52  */
53 class StaticDemoTester{
54   public void test(){
55     //you call a static method using the class name
56     int numCreated = StaticDemo.getNumCreated();
57     StaticDemo.printAllStaticInfoAvaliable();
58     
59     StaticDemo staticDemo=new StaticDemo("demo3");
60     //instance is needed to call non static method
61     staticDemo.printAllInfoAvaliable();
62     //this works, but is sloppy, should access from class not instance
63     staticDemo.printAllStaticInfoAvaliable();
64   }
65 }