1CMSC 131 Spring 2007Jan Plane (adapted from Bonnie Dorr)Lecture 9:Objects and Classes in JavaNote: This set of lecture slides will most likely take more than one day to complete and it is closely tied to a Student class and driver developed during the lectureLast time:1.Pseudo-code (from last lecture)2.Objects and classes3.Heaps4.Garbage Collection 5.Aliasing6.Object equalityToday:1.More about Creating Objects and classes in Java2.Methods3.Constructors, Accessors, Mutators4.Equality5.Printing an objectCMSC 131 Spring 2007Jan Plane (adapted from Bonnie Dorr)1Classes in JavaClass declarations have the following form in Java:public class Student {}When you create a class in Eclipse, it generates this template for youVisibility modifier:more later in classclass keyword class nameclass body: instance variables, methodsCMSC 131 Spring 2007Jan Plane (adapted from Bonnie Dorr)2Anatomy of an Instance Variable Declarationpublic int IDNum;Visibility modifier Normal variable ceclaration2CMSC 131 Spring 2007Jan Plane (adapted from Bonnie Dorr)3Method Declarations in JavaMethods are operations, like +, ++, etc.They can take inputsThey can return valuesThey can modify instance variablesThe form varies slightly depending on whether values are returned or notCMSC 131 Spring 2007Jan Plane (adapted from Bonnie Dorr)4… for methods that do not return valuespublic void acceptTokens (int tokensPassedIn){tokenLevel = tokenLevel + tokensPassedIn;…}Anatomy of a Method Declaration (1)Visibilitymodifiervoidkeywordmethod name parameter listbodyCMSC 131 Spring 2007Jan Plane (adapted from Bonnie Dorr)5“void” return type“Parameter List”If a method does not return a value, use the void keywordThe parameter list describes the form of inputs:typename (for use in body)Parameter lists may be empty: ()Multiple parameters are separated by: ,3CMSC 131 Spring 2007Jan Plane (adapted from Bonnie Dorr)6Anatomy of a Method Declaration (2)… for methods that return valuespublic int lastFour (){… return id % 10000;}Visibilitymodifierreturntypemethod name parameter listbodyCMSC 131 Spring 2007Jan Plane (adapted from Bonnie Dorr)7Return TypeMethods that return values must specify the type of the value to be returnedThe bodies of these methods use return to indicate when a value is to be returnedThe value being returned must have the same type as the return typeCMSC 131 Spring 2007Jan Plane (adapted from Bonnie Dorr)8Object CreationOnce a class is defined, objects based on that class can be created using new:new Student ()To assign an object to a variable, the variable’s type must be the class of the objectStudent s = new Student ();Each object has its own copies of all the instance variables in the class (except for certain kinds we’ll study later)Instance variables and methods in an object can be accessed using “.”s.IDNum = 123456789;s.setIDNum (123456789);4CMSC 131 Spring 2007Jan Plane (adapted from Bonnie Dorr)9ConstructorsSpecial “methods” in class definitions to specify how objects are createdForm of a constructor definition:Student (String nameDesired, int IDDesired, inttokensDesired) {name = nameDesired;id = IDdesired;tokenLevel = tokensDesired;}Can have more than one constructor, provided argument lists are differentStudent (int IDDesired) {id = IDDesired;}Java includes default constructor (no arguments), which you can redefine (override)Student () {tokenLevel = 3;}CMSC 131 Spring 2007Jan Plane (adapted from Bonnie Dorr)10Equality Testing• Need to defined what it means for two students to be equal• You can define it however you likepublic boolean equals (Student otherStudent) {return id == otherStudent.id;}CMSC 131 Spring 2007Jan Plane (adapted from Bonnie Dorr)11Objects to StringsWhat happens if we try to print a Student object?invoke println using a Student object as an argument?Student s1 = new Student ();System.out.println (s1);Something like this prints:Student@82ba415CMSC 131 Spring 2007Jan Plane (adapted from Bonnie Dorr)12Java Knows “How” To Print Any ObjectWhy? Every class has a default toString methodtoString converts objects into stringsSystem.out.println calls this method to print an objectDefault: object type and addresstoString can be overridden!// The method for converting Students to stringspublic String toString () {return (name + “: ” + id);}CMSC 131 Spring 2007Jan Plane (adapted from Bonnie Dorr)13Static Data Members and Static MethodsNot contained in or associated with an object of that typeAccessed by the ClassName.variableNameor by ClassName.methodNamerather than by objectName.variableName or by objectName.methodNameCMSC 131 Spring 2007Jan Plane (adapted from Bonnie Dorr)14for LoopsThree kinds of loops in Javawhiledo … whileforA common programming idiomint i=0;while (i <= 10) {j += i;i++;}Equivalent for-loopfor (int i=0; i<=10; i++)j += i;6CMSC 131 Spring 2007Jan Plane (adapted from Bonnie Dorr)15for -Loop Formfor (<init>; <continue>; <increment>) <stmt>Equivalent to:<init>;while (<continue>) {<stmt>;<increment>;}Any of the three <init> / <continue> / <increment> components may be omittedfor (;;) { …}Runs forever!CMSC 131 Spring 2007Jan Plane (adapted from Bonnie Dorr)16Comments… allow you to insert explanations in your codeTwo form:// blah blah blah/* blah blah blah */Every:Class declarationInstance variable declarationMethod declarationmust have a comment explaining its purpose!CMSC 131 Spring 2007Jan Plane (adapted from Bonnie Dorr)17Set / Get MethodsWe have been using = to modify instance variables and accessing variables directly to read valuesGenerally, this is not good practice because it imposes restrictions on class implementationBetterset methods to set values (mutators)get methods to read values (accessors)7CMSC 131 Spring 2007Jan Plane (adapted from Bonnie Dorr)18Set Methods (Mutators)public void setID (int newID) {id = newID;}Can also do consistency checkingpublic void setTokenLevel (int newTokenLevel) {if (newTokenLevel <= 3) {tokenLevel = newMonth;} else {System.out.println ("Bad argument to setTokenLevel: " + newTokenLevel);}CMSC 131 Spring 2007Jan Plane (adapted from Bonnie Dorr)19Get Methods (Accessors)Sole purpose is to return values of statepublic int getID () {return id;}Why use them?The state information may not always be stored in a single
View Full Document