From: <ne...@ho...> - 2002-08-14 23:39:59
|
Since foo/bar/baz seems a little abstract, I thought I'd give a more concrete example. import java.util.*; public class Widget { // for some reason, we want to keep track of all widgets that have been created; this is not a good idea or a good way to do this.. it's just an example; this is static since we need to keep just one global list private static List allWidgets = new LinkedList(); // this is non-static; each widget instance will have it's own name private String name; public Widget(String name) { this.name = name; allWidgets.add(this); } public String getName() { // this won't compile because name is not static //return Widget.name; // this will work //return this.name; return name; } public static int getCount() { // this won't compile; no 'this' in a static method //return this.allWidgets.size(); // this will work //return Widget.allWidgets.size(); return allWidgets.size(); } public static Iterator getAllWidgets() { return allWidgets.iterator(); } public static void main(String[] args) { // by convention, your reference (instance) names should be in lower-case so you can distinguish them from class names, which should be in upper-case Widget a = new Widget("Car"); Widget b = new Widget("Banana"); // this is the preferred way to refer to a static member (through it's class name) System.out.println("There are " + Widget.getCount() + " widgets."); // this is legal but may cause confusion; the count doesn't belong to a, but to the entire class System.out.println("There are " + a.getCount() + " widgets."); // it's clear that the name belongs to a single widget System.out.println("Widget a is named: " + a.getName()); // this will not compile since getName() is not static; without a widget instance, you have no name, you have no name System.out.println("Widget a is named: " + Widget.getName()); } } |