CMSC 202 Classes and Objects Aug 6 2007
CMSC 202 Classes and Objects Aug 6, 2007
Programming Languages ¢ ¢ ¢ 2 All programming languages provide some form of abstraction Procedural language (eg C) abstraction requires thinking in terms of the underlying computer (data areas, sequential statement execution) Object-oriented languages allow abstraction of the elements of the problem Aug 6, 2007
Objects ¢ ¢ Elements in the problem are referred to as objects Examples l l l ¢ Each object has l l 3 Car Bank account String State represented by internal data Behaviors produced by methods Adapted from "Thinking in Java" by Bruce Eckel Aug 4, 2008
What’s a class ¢ From the dictionary l l ¢ From OOP (Rumbaugh, et al) l ¢ 4 a kind or category A set, collection, group, or configuration containing members regarded as having certain attributes or traits in common A class describes a group of objects with similar properties, common behavior, common relationships with other objects, and common semantics Examples July 21, 2008
Classes All objects are unique ¢ Objects which are identical except for their state can be grouped into a class ¢ Class of cars l Class of birds l Class of playing cards l ¢ 5 Defining classes is a fundamental concept in OOP Aug 6, 2007
A class is a model ¢ ¢ A class is a model for a group of objects The focus of the class is the common behavior of the objects the class models. A class’ behavior may also referred to as a service, operation, action, or command. The model also contains common attributes of the objects l 6 The attributes exit to support the model’s behaviors July 21, 2008
A class is a type Variables of the class type may be created just like variables of built-in types ¢ You can create as many objects of the class type as you like ¢ OOP challenge is to create the objects that match the problem ¢ 7 Aug 6, 2007
Object Interface ¢ ¢ The requests you can make so an object will do something are determined by its interface The interface is determined by its type TYPE Light. Bulb on( ) off( ) INTERFACE brighten( ) dim( ) 8 Adapted from "Thinking in Java" by Bruce Eckel Aug 6, 2007
Implementation ¢ ¢ ¢ 9 Code and hidden data within the object that satisfies the requests comprise the implementation Each request in the interface has an associated method. When a particular request is made, that method is called. In OO-speak we say that you are “sending a message” to the object which responds to the message by executing the appropriate code. Adapted from "Thinking in Java" by Bruce Eckel Aug 6, 2007
Class Definitions ¢ You already know how to use classes and the objects created from them, and how to invoke their methods For example, you have already been using the predefined String l Now you will learn how to define your own classes and their methods, and how to create your own objects from them l 10 Copyright © 2008 Pearson Addison-Wesley. All rights reserved Aug 6, 2007
A Class Is a Type ¢ ¢ A class is a special kind of programmer-defined type, and variables can be declared of a class type A value of a class variable type is called an object or an instance of the class l If A is a class, then the phrases • “X is of type A“ • “X is an object of the class A" • “X is an instance of the class A" mean the same thing A class determines the actions it can perform and the types of data that required to support those actions ¢ 11 Copyright © 2008 Pearson Addison-Wesley. All rights reserved Aug 6, 2007
The Class Definition ¢ ¢ A class definition implements the class model The class behaviors/services/actions/operations are implemented by class methods. The class attributes (data items) are called fields or instance variables. In Java, classes are defined in files with the. java extension. The name of the file must match the name of the class defined within it. 12 Copyright © 2008 Pearson Addison-Wesley. All rights reserved Aug 6, 2007
Objects ¢ ¢ All objects of a class have the same methods All objects of a class have the same attributes (i. e. , name, type, and number) l l 13 For different objects, each attribute can hold a different value The values of the attributes define the object state which is what makes each object unique. Copyright © 2008 Pearson Addison-Wesley. All rights reserved July 21, 2008
Class Examples ¢ What services/behaviors might be appropriate for the following things A red-green-yellow traffic light l A garage door opener l A bank account l 14 Aug 6, 2007
Anatomy of a Java Class Visibility modifier (More on this later) public Keyword class Name of the class Date 1 { Class body: instance variables, methods } NO semi-colon 15 Aug 6, 2007
Instance Variables ¢ ¢ ¢ are defined inside the class definition. may be primitive types or other class types are accessible by all methods of the class l ¢ 16 i. e. have “class scope” Given the services identified for the redgreen-yellow traffic light, the garage door opener and the bank account, what instance variables might be defined for each? Aug 6, 2007
Anatomy of a method Class methods are very much like functions. Methods include a visibility modifier, return type, method name, and optional parameters Visibility modifier (More on this later) public Name of the method return type double to. Celcius Optional parameters (double f. Temp) { Method code: local variables and statements }
A Date Class The code below defines a class named Date 1. This class definition goes in a file named Date 1. java public class Date 1 { public String month; public int day; public int year; These are the (public)“data members” or “instance variables” of the class This is a method definition and its implementation public void print( ) { System. out. println(month + “ “ + day + “, “ + year); } } A method may use the class’ instance variables 18 Aug 6, 2007
Date 1 print is a method of the Date 1 class. Its definition and implementation are part of the Date 1 class. Like functions in C, class methods may be void, return a value, and (optionally) have parameters. Method parameters may be primitive types passed by value or may be objects (which need further discussion later). All class methods have access to all class instance variables. 19 Aug 6, 2007
Using Date 1 We can create instances of Date 1, modify, and print the date. This class definition (program) goes in a file named Date 1 Demo. java public class Date 1 Demo { public static void main( String[ ] args ) { Create a Date 1 object Date 1 my. Date; my. Date = new Date 1( ); named my. Date. month = “July”; my. Date. day = 4; my. Date. year = 2007; Give values to the data members my. Date. print( ); Invoke the print method } } 20 Aug 6, 2007
Creating the Date 1 Object The statement Date 1 my. Date; defines a variable of type Date 1. But there is no Date 1 object yet! The statement my. Date = new Date 1( ); creates a “new” Date 1 object and names it with the variable “my. Date”. Now “my. Date” refers to a Date 1 object For convenience, these statements can be combined Date 1 my. Date = new Date 1( ); (continued) 21 Aug 6, 2007
“Dot” notation Public instance variables of an object are referenced using the “dot” operator (like members of a struct in C) my. Date. month = “July”; my. Date. day = 4; my. Date. year = 2007; Instance variable can be used like any other variable of the same type. The set of values stored in all instance variables define the state of the my. Date object. (continued) 22 Aug 6, 2007
“Dot” notation The print method of my. Date is invoked using the “dot” operator (again similar to accessing a member in a C struct). The statement my. Date. print( ); invokes the print method of my. Date which refers to an object of type Date 1. In OO terminology we say that we are “sending the print message” to the object referred to by my. Date. The object my. Date is referred to as the “calling object” or “host object”. It is the object in which the print method is invoked. 23 Aug 6, 2007
Other Date Methods Some other possible services which the Date class might provide include • • 24 increment. Day - changes the date to “tomorrow” print. DMY - a different printing format set. Date - initialize/change the year, month, and/or day What others ? Aug 6, 2007
New Date 1 Methods // change the month (using an int), day, and year. public void set. Date( int new. Month, int new. Day, int new. Year ) { month = month. String( new. Month ); day = new. Day; year = new. Year; } // change month number (int) to string - used by set. Date public String month. String( int month. Number ) { switch ( month. Number ) { case 1: return "January"; case 2: return "February"; case 3: return "March"; case 4: return "April"; case 5: return "May"; case 6: return "June"; case 7: return "July"; case 8: return "August"; case 9: return "September"; case 10: return "October"; case 11: return "November"; case 12: return "December"; default: return “? ? ”; } }
Confusion ¢ In the preceding set. Date method it’s tempting to define the method using the common terms “month”, “day” and “year” as the parameters. public void set. Date( int month, int day, int year) { month = month. String( month ); // which month is which? day = day; // which day is which? year = year; // which year is which? } The problem with this code is that the compiler assumes that all uses of day, month, and year refer to the method parameters and hence this code has no effect. 26 Jan 23, 2008
Calling Object When any class method is called, the instance variables used within the method are assumed to belong to the calling object. What the code in set. Date is really trying to do is public void set. Date( int month, int day, int year) { “calling object”. month = month. String( month ); “calling object”. day = day; “calling object”. year = year; } It’s handy (and sometimes necessary) to have a name for the calling object. In Java, we use the reserved word this as the generic name of the calling object. (continued) 27 Jan 23, 2008
Using this So, if we want to name our parameters the same as our instance variables, we could write the set. Date method as public void set. Date( int month, int day, int year) { this. month = month. String( month ); this. day = day; this. year = year; } Note that many examples in the text use this technique for class methods and some Java programmer tools (including Eclipse) use this technique when writing code for you. 28 Jan 23, 2008
this again As a final example, recall the print method from Date 1 public void print( ) { System. out. println(month + “ “ + day + “ “ + year); } Here it’s clear that month, day, and year refer to the instance variables of the calling object because there are no parameters. To be more explicit we could have written public void print( ) { System. out. println(this. month + “ “ + this. day + “ “ + this. year); } With no chance for confusion, using the prefix this is unnecessary and usually omitted. 29 Aug 6, 2007
Method Documentation ¢ Clear communication with the class user is of paramount importance so that he can l l ¢ Method comments: l l ¢ explain what the method does, and describe how to use the method. Two important types of method comments: l l 30 use the appropriate method, and use class methods properly. precondition comments post-conditions comments Aug 6, 2007
Preconditions and Postconditions ¢ Precondition What is assumed to be true when a method is called l If any pre-condition is not met, the method cannot correctly perform its function. l ¢ Postcondition Describes the effect of the method l States what will be true after the method executes (assuming all pre-conditions are met) l 31 Aug 6, 2007
A Simple Example Recall the print method from Date 2 that outputs the month string, day, and year to the screen. The print method might look something like this: /* Pre. Condition: none Post. Condition: The calling object has been written to the screen in the format <month string> <day>, <year> */ public void print( ) { // code here } 32 Aug 6, 2007
Another Common Example Very often the precondition specifies the limits of the parameters and the postcondition says something about the return value. /* Pre-condition: 1 <= month <= 12 day appropriate for the month 1000 <= year <= 9999 Post-condition: The month, day, and year of the calling object have been set to the parameter values. Returns true if the calling object has been changed. Returns false otherwise */ public boolean set. Date( int month, int day, int year) { // code here } 33 Aug 6, 2007
Date 1 Code Example Date 1 new. Years = new Date 1( ); new. Years. month = “January”; new. Years. day = 1; new. Years. year = 2008; Date 1 birthday = new Date 1( ); birthday. month = “July”; birthday. day = 4; birthday. year = 1776; new. Years. print( ); birthday. print( ); System. out. println(birthday. month. String(6)); birthday. set. Date( 2, 2, 2002); birthday. print( ); new. Years. day = 42; new. Years. print( ); 34 // // line line 1 2 3 4 5 6 7 Sept 7, 2007
January 42, 2008 It appears that classes allow the user to change the data anytime he chooses and can possibly make the data invalid That’s true so far because we have defined our instance variables with public access. This is rarely the case in real applications. Our focus today was on classes vs objects and the syntax used for accessing methods. Next time we’ll see a more robust class that will prevent the user from making our data invalid. 35 Sep 7, 2007
- Slides: 35