Program 6.12: A Web Site Class with a static version

Program 6.12 is a website class with a static version field and getVersion method.

public class website {

  String name;
  String url;
  String description;
  static String version = "1.0";

  public website(String n, String u, String d) {
    name = n; 
    url  = u;
    description = d;
  }

  public static String getVersion() {
    return version;
  }

  public String getName() {
    return name;
  }

  public String getURL() {
    return url;
  }

  public String getDescription() {
    return description;
  }

  public void setName(String s) {
    name = s;
  }

  public void setURL(String s) {
    url = s;
  }

  public void setDescription(String s) {
    description = s;
  }

  public String toString() {
    return  (name + " at " + url + " is " + description);
  }

}
If a method is declared static, you access it by using the class name rather the name of a particular instance of the class. Therefore instead of writing

website w = new website("Cafe Au Lait",
  "http://sunsite.unc.edu/javafaq/", 
  "Really cool!");
String s = w.getVersion();
you just write

String s = website.getVersion();

Static methods may not call non-static methods or members of the same class directly. Rather they must specify which instance of the class they are referring to. Trying to call a non-static method or member is a very common compile time error. The specific error message generated by the javac compiler will look something like this

Error: Can't make static reference to method void print() in class test.

Of course the names and signature will be changed to match the specific method and class.


Copyright 1996 Elliotte Rusty Harold
elharo@sunsite.unc.edu
This Chapter
Examples
Home