Sullivan Market

a web based full-circle development system



My Java Tutorials - Static Methods

Static Methods:
    Static methods are methods that are throughout the whole class, not just an instance.
Below you see the different ways in which protected static methods, private static methods
and public static methods are accessed. Note that you can never use the keyword "this"
with a static variable.

For Example...

1 public class CountInstances {
2 private static int numInstances = 0;
3
4 protected static int getNumInstances() {
5 return numInstances;
6 }
7
8 private static void addInstance() {
9 numInstances++;
10 }
11
12 CountInstances() {
13 CountInstances.addInstance();
14 }
15
16 public static void main(String[] arguments) {
17 System.out.println("Starting with " +
18 CountInstances.getNumInstances() + " instances");
19
20 for (int x = 0; x < 10; x++) {
21 New CountInstances.getNumbInstances();
22 }
23
24 System.out.println("Created " +
25 CountInstances.getNumInstances() + " instances");
26 }
27 }

Back To Java Tutorials

©2012 SullivanMarket.com