CSC152 2005S, Class 11: Object Basics, Continued Admin: * No reading for Friday! * More lecture! * Code online. Overview: * Questions and answers * Writing constructors * Testing our Fraction class * Three kinds of classes * Standard object methods Questions: * What is a field, how does it relate to a variable? * Fields are very much like variables in that they have types and store values * Variables tend to live only as long as the method that contains them. * Fields live "longer" - As long as the object that contains them * We use them more-or-less the same way within a method * To help us remember that we're referring to a field (part of an object) rather than a variable or parameter (part of a method), we use objectName.fieldName * When a method is to use "the current object", we use "this" as the object name. * What are we going to return from add? * A Fraction! /Writing constructors/ * Reminder: Constructors are methods that build objects * In Java, there is a particular syntax that distinguishes "basic" constructor from other methods * These construtors are associated with the "new" keyword * Form: Combine the type and the name into "The name of the class" PROTECTION NameOfClass(parameters) { BODY; } * Example: public Fraction(BigInteger _num, BigInteger _denom) { } // Morals: * toString() methods are your friends * We tend to create a lot of objects * You can often skip the "toString" when you want to convert an object to a string and Java will "figure it out" Short "documentation reading" problem. Friday: Lots of cool additional methods (including testing) Observation: * We've seen three "kinds" of classes * "Mold" classes provide templaets for building objects (e.g., Fractions) * "Main" classes: Provide a main method which builds objects and tells 'em to do things * "Helper" classes: Provide methods that do things to other objects Integer.toString(5);