******************************************************************************* 0) Last time- all about methods - chapter 3 quiz 1) Administrative - hw: continue A1 - read 4.5, 4.6, 4.10 (no presentations) 2) How to write an instantiable class Program idea: simulate the second "hand" on a digital clock Requirements: be able to "tick" the clock and display the time Classes: main class (main method will be where we tell it to tick) Counter class (will count ticks and wrap after hitting limit) Counter class: (diagram) - data members: -count, +LIMIT - constructor: assigns initial values (constructors ALWAYS do) - methods: tick(), getCount(), printCount() * notice how the data members "belong" to the counter * private data, except unchangeable ones, and public methods * notice the difference between returning and printing Main class: how we'll use a Counter (assume it exists) - coding now (online) Counter seconds = new Counter(60); seconds.tick(); seconds.printCount(); seconds.tick(); int time = seconds.getCount(); S.o.p("Clock has ticked " + time + " times."); S.o.p("Clock's limit is " + seconds.LIMIT + "."); * what you CAN'T do: seconds.count++; (good, b/c might not wrap!) Code Counter class now, and run it: outline comments first! public Counter(int limit) { LIMIT = limit; }; public void tick() { int nextCount= (count+1)%LIMIT; count= nextCount;} * mod is a good way to do cyclical counting * note the local variables that don't exist anywhere else * but the data members are reachable from anywhere in the class * we DON'T re-declare the data members anywhere- only at the top * anywhere we say "count" there's an implicit "this.count" * we could have just used "60", but a constant is better (why?) Memory diagram of main class, and program flow 3) Exercises to modify this class A) Keep track of the # of counter objects created using a data member. - how can we do that? variable gets incremented in constructor - it has to be static (only one copy, not associated with object) - use it by making a getObjectCount() method and a minute counter B) Make it possible to start the count somewhere other than 0 - make two constructors, so you can use either one - "overloading": same name, different parameters - change original to use this one so we don't duplicate code (this) - make sure it can't start at or past the limit! (use Math.min) - use it in main C) Make it possible to compare two counters and return the higher count. - method that takes another counter as parameter - compare this.count with parameter.count using Math.max 4) Summary - pieces of an instantiable class and how to write them - visibility, constants, and static members - how data members and local variables are used in the methods - how to make a class that fulfills specific requirements *******************************************************************************