DOC PREVIEW
UMD CMSC 131 - Lecture 9: Objects and Classes in Java

This preview shows page 1-2 out of 7 pages.

Save
View full document
View full document
Premium Document
Do you want full access? Go Premium and unlock all 7 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 7 pages.
Access to all documents
Download any document
Ad free experience
Premium Document
Do you want full access? Go Premium and unlock all 7 pages.
Access to all documents
Download any document
Ad free experience

Unformatted text preview:

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 JavaClass 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 JavaMethods are operations, like +, ++, etc.They can take inputsThey can return valuesThey can modify instance variablesThe 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 keywordThe parameter list describes the form of inputs:typename (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 TypeMethods that return values must specify the type of the value to be returnedThe bodies of these methods use return to indicate when a value is to be returnedThe value being returned must have the same type as the return typeCMSC 131 Spring 2007Jan Plane (adapted from Bonnie Dorr)8Object CreationOnce 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)9ConstructorsSpecial “methods” in class definitions to specify how objects are createdForm 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 StringsWhat 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 ObjectWhy? Every class has a default toString methodtoString converts objects into stringsSystem.out.println calls this method to print an objectDefault: object type and addresstoString 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 MethodsNot contained in or associated with an object of that typeAccessed by the ClassName.variableNameor by ClassName.methodNamerather than by objectName.variableName or by objectName.methodNameCMSC 131 Spring 2007Jan Plane (adapted from Bonnie Dorr)14for LoopsThree kinds of loops in Javawhiledo … whileforA 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 codeTwo form:// blah blah blah/* blah blah blah */Every:Class declarationInstance variable declarationMethod declarationmust have a comment explaining its purpose!CMSC 131 Spring 2007Jan Plane (adapted from Bonnie Dorr)17Set / Get MethodsWe have been using = to modify instance variables and accessing variables directly to read valuesGenerally, this is not good practice because it imposes restrictions on class implementationBetterset 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

UMD CMSC 131 - Lecture 9: Objects and Classes in Java

Documents in this Course
Set #3

Set #3

7 pages

Exam #1

Exam #1

6 pages

Exam #1

Exam #1

6 pages

Notes

Notes

124 pages

Notes

Notes

124 pages

Load more
Download Lecture 9: Objects and Classes in Java
Our administrator received your request to download this document. We will send you the file to your email shortly.
Loading Unlocking...
Login

Join to view Lecture 9: Objects and Classes in Java and access 3M+ class-specific study document.

or
We will never post anything without your permission.
Don't have an account?
Sign Up

Join to view Lecture 9: Objects and Classes in Java 2 2 and access 3M+ class-specific study document.

or

By creating an account you agree to our Privacy Policy and Terms Of Use

Already a member?