Java Reference
In-Depth Information
public Dog() { }
public static int woofCount() { return woofCounter; }
public void woof() { woofCounter++; }
}
class Cat {
private static int meowCounter;
public Cat() { }
public static int meowCount() { return meowCounter; }
public void meow() { meowCounter++; }
}
The Ruckus class is unchanged with the exception of the two print statements, which are modified
to use the new method names to access the counts:
System.out.print(Dog. woofCount () + " woofs, ");
System.out.println(Cat. meowCount () + " meows");
In summary, static fields are shared by their declaring class and any subclasses. If you need a
separate copy of a field for each subclass, you must declare a separate static field in each subclass.
If you need a separate copy for each instance, declare a nonstatic field in the base class. Also, favor
composition over inheritance unless the derived class really is a kind of the base class.
< Day Day Up >
 
 
Search WWH ::




Custom Search