//Date3.java // static members examples public class Date3 { //********** static variables *************** //** static variable ("class variable") is per class, not per object. //one for the entire class. each object does not have its own copy. private static int numberDates=0; //common example is an object counter variable. //incremented in each constructor, //private so only this class can directly access it. //**final is a constant. can not be changed. //conventional to be in all caps and _ //accessed thru class name: Date3.VALID_START_YEAR //examples: Math.PI Integer.MAX_VALUE public static final int VALID_START_YEAR=1584; //pretend... //**if not static, is instance variable. each object has own copy. //********** instance variables *************** private int year; private int month; private int day; //********** constructors *************** public Date3() { month = 1; day = 1; year = 1970; numberDates++; //*** OR: Date3.numberDates++; } public Date3(int newMonth, int newDay, int newYear) { month = newMonth; day = newDay; year = newYear; numberDates++; //*** } public Date3( Date3 other) { month = other.month; day = other.day; year = other.year; numberDates++; //*** } public Date3( String date) { java.util.StringTokenizer st = new java.util.StringTokenizer(date,"/"); month = Integer.parseInt(st.nextToken()); //extract next token day = Integer.parseInt(st.nextToken()); year = Integer.parseInt(st.nextToken()); numberDates++; //*** } //********** accessor methods *************** public int getYear() { return year; } public int getMonth() { return month; } public int getDay() { return day; } public String toString() { return(month + "/" + day + "/" + year); } //** static method is per class. each object does not have own copy. //can only access static variables because there are no instance variables //because there is no object. //accessed thru class name: Date3.getNumberDates() public static int getNumberDates() { return numberDates; } //********** mutator methods *************** public void increment() { day++; //stub for the actual method to be written later... } //**another static method example public static void clearNumberDates() { numberDates = 0; } //** static method can provide a service/utility. not associated //with any object. //Examples: Math.sqrt JOptionPane.showInputDialog Integer.parseInt public static boolean isValidDay(int month, int day, int year) { //bunch of code will go here to determine if month day year //combination is valid or not. return true; //or false... } } /* client code: if (myYear < Date3.VALID_START_YEAR) System.out.println("Years before "+Date3.VALID_START_YEAR+" are no good"); //each Date3 object created increments the numberDates variable. //client can learn its value: System.out.println("Number of Date objects created:"+Date3.getNumberDates()); //reset the application. dispose of all date objects, then: Date3.clearNumberDates(); //use the valid day combo checker: if (Date3.isValidDay(m,d,y))... */