CSC152 2005F, Class 23: Review of Template Classes Admin: * Approximate schedule for this week * Questions on homework? * New homework: To be determined at the end of class Overview * What is a class? Three perspectives. * Parts of a template class. * Extended example. Programs in Java combine classes and objects * You write some of the classes; others come with the language * Classes serve three primary roles within programs: * One designated Main Class holds the main method. * Describes how the other classes fit together. * Some number of Utility Classes collect useful methods * The Math class provides sqrt, tan, atan, etc. * Most utility methods are called with ClassName.methodname(params) double d = Math.atan(Math.sqrt(2.0) + Math.tan(1.0)); * Most classes are Template Classes, which describe how to build and use objects * Classes can serve more than one of these roles. Template classes model groups of similar objects: * Describe what data we will associate with each object * Describe how the object does things * Describe how to build new objects (and what data we need) Describing data: * Called "fields" * Declarations look (almost) excactly like variable declarations TYPE NAME; * "I can use this name as a value of that type within *the methods of this class." * Unlike variables, which are restricted to one method, fields are shared between methods * Within methods we should refer to the fields as "this.NAME". * Although we may just use "NAME" * We use "this" for clarity * To distinguish it from variables which potentially have the same name * To distinguish the fields in the current object from fields in other objects * We refer to those fields as otherObjectName.fieldName * The value associated with a field *can* (and often does) change throughout the executation of a program * The name and number of fields does not The example begins: PiggyBank * Another way to think about fields is that they provide the "characteristics" of the object; * What distinguishes one object in a class from another object in the same class. Classes are more interesting when they do things. "Methods" describe how. public return-type name(params) { body return value-of-designated-type; } * return-type may be "void" for "I don't compute anything" * params may be empty * nonempty params is a sequence of "Type name" pairs separated by commas * If you don't write "public", the method is usable only by other objects in the same class (or the same object) * N kinds of protection: public, private, "nothing", protected * Don't worry about this issue right now. EXAMPLE CONTINUES