CMSC 202 Classes and Objects The Basics Version
CMSC 202 Classes and Objects: The Basics Version 9/09
Programming & Abstraction • All programming languages provide some form of abstraction. – Also called information hiding – Separating how one uses a program module from its implementation details • Procedural languages: – Data abstraction: using data types – Control abstraction: using functions • Object-oriented languages: – Data and control abstraction: using classes • Our world is object-oriented. Version 9/09 2
Making a Sandwich • Procedural ham sandwich – – grind wheat, bake bread, kill pig, cure ham milk cow, make cheese put ham on bread, put cheese on ham, put bread on cheese • Object-oriented ham sandwich – – ask baker for bread, ask butcher for ham, ask milkman for cheese, put ham on bread, put cheese on ham, put bread on cheese • What are the objects in the object-oriented approach? Version 9/09 3
What’s a Class? • From the dictionary – A kind or category – A set, collection, group, or configuration containing members regarded as having certain attributes or traits in common. • From OOP (Rumbaugh, et al) – A group of objects with similar properties, common behavior, common relationships with other objects, and common semantics. – We use classes for abstraction purposes. Version 9/09 4
Classes • All objects are unique. • Objects that are identical except for their state can be grouped into a class. – Class of cars – Class of birds – Class of playing cards – Class of bakers Version 9/09 5
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. – The attributes exist to support the model’s behaviors. Version 9/09 6
A Class is a Type An Object is a Variable • Variables of the class type (objects) may be created just like variables of built-in types. – All bakeries have similar (class) properties. • You can create as many objects of the class type as you like. – There is more than one baker in Baltimore. • OOP challenge is to define the classes and create the objects that match the problem. – Do we need a farmer class? Version 9/09 7
Object Interface • The requests you can make so an object will do something are determined by its interface. • The interface is determined by its class type. • IMPORTANT – Do you need to know how a bakery works to get bread? – Who needs to know how a bakery works? TYPE Bakery make. Bagel() INTERFACE make. Bread() sell. Bagel() sell. Bread() Version 9/09 8
Implementation • Code and hidden data in the object that satisfies requests comprise the implementation. – What’s hidden in a bakery? • 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. Version 9/09 9
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 class. String name = “Fido”; System. out. println(“name length = “ + name. length()); Version 9/09 Copyright © 2008 Pearson Addison-Wesley. All rights reserved 10
A Class Is a Type • A class is a programmer-defined type. • 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. – 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 Version 9/09 Copyright © 2008 Pearson Addison-Wesley. All rights reserved 11
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. – e. g. class ‘Baker’ must be in Baker. java Version 9/09 Copyright © 2008 Pearson Addison-Wesley. All rights reserved 12
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). – 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. Version 9/09 Copyright © 2008 Pearson Addison-Wesley. All rights reserved 13
Class Examples • What services/behaviors might be appropriate for the following things? – A red-green-yellow traffic light – A garage door opener – A bank account Version 9/09 14
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 } Version 9/09 NO semi-colon 15
Instance Variables • Defined inside the class definition • May be – primitive types – other class types • Are accessible by all methods of the class – have class scope • Given the services identified for the red-greenyellow traffic light, the garage door opener and the bank account, what instance variables might be defined for each? Version 9/09 16
Anatomy of a Method Are very much like functions 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 } Version 9/09 17
Example: A Date Class 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 public String to. String( ) This is a method definition and its implementation { return month + “ “ + day + “, “ + year; } } A method may use the class instance variables Version 9/09 18
Date 1 to. String Method • to. String is a method of the Date 1 class. – Its definition and implementation are part of the Date 1 class. • Class methods may – be void or return a value, and – (optionally) have parameters, which may be • primitive types passed by value, and/or • objects (discussed later). • All of a class’ methods have access to all of the class’ instance variables (class scope). Version 9/09 19
Using Date 1 This class definition 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; named my. Date = new Date 1( ); my. Date. month = “July”; my. Date. day = 4; my. Date. year = 2007; Give values to the data members String date. String = my. Date. to. String( ); System. out. println(date. String); } Invoke the to. String method } Version 9/09 20
Creating the Date 1 Object • The statement Date 1 type Date 1. my. Date; defines a variable of – 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( ); Version 9/09 21
“Dot” Notation • Public instance variables of an object are referenced using the “dot” operator. my. Date. month = “July”; my. Date. day = 4; my. Date. year = 2007; • Instance variables 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. Version 9/09 22
More “Dot” Motation • The statement my. Date. to. String( ); invokes the to. String method of my. Date, which refers to an object of type Date 1. • In OO terminology, we say that we are “sending the to. String message” to the object referred to by my. Date. • The object my. Date is referred to as the calling object or host object. Version 9/09 23
Other Date Methods Some other possible services that the Date 1 class might provide: • increment. Day - changes the date to “tomorrow” • DMYString – creates a different string format • set. Date - initialize/change the year, month, and/or day • What others ? Version 9/09 24
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 “? ? ”; } } Version 9/09 25
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 compiler assumes that all uses of day, month, and year refer to the method parameters and hence this code has no effect. Version 9/09 26
Calling Object When any class method is called, the instance variables used within the method are assumed to belong to the calling/host 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. Version 9/09 27
Using this So, if we want to name our parameters the same as our instance variables: public void set. Date( int month, int day, int year) { this. month = month. String( month ); // notice “this” this. day = day; this. year = year; } Note: • Many examples in the text use this technique for class methods. • Some Java programmer tools (including Eclipse) use this technique when writing code for you. Version 9/09 28
this Again Recall the to. String method from Date 1: public void to. String( ) { return month + “ “ + day + “ “ + year; } It’s clear that month, day, and year refer to the instance variables of the calling object because there are no parameters. We could have written: public void to. String( ) { return this. month + “ “ + this. day + “ “ + this. year; } If the prefix this is unnecessary, it is usually omitted. Version 9/09 29
Method Documentation • Clear communication with the class user is of paramount importance so that he can – use the appropriate method, and – use class methods properly. • Method comments: – explain what the method does, and – describe how to use the method. • Two important types of method comments: – precondition comments – post-conditions comments Version 9/09 30
Preconditions and Postconditions • Precondition – What is assumed to be true when a method is called – If any pre-condition is not met, the method may not correctly perform its function. • Postcondition – States what will be true after the method executes (assuming all pre-conditions are met) – Describes the effect of the method Version 9/09 31
A Simple Example The to. String method might look something like this: /* Pre. Condition: none Post. Condition: The calling object is returned in the format <month string> <day>, <year> */ public void to. String( ) { // code here } Version 9/09 32
Another 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 } Version 9/09 33
Sample Code Segment Using 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; System. out. println(new. Years. to. String( )); System. out. println(birthday. month. String(6)); birthday. set. Date( 2, 2, 2002); System. out. println(birthday. to. String( )); new. Years. day = 42; System. out. println(new. Years. to. String( )); Version 9/09 // // line line 1 2 3 4 5 6 7 34
January 42, 2008 • It appears that classes allow the user to change the data anytime he or she chooses, possibly making 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. Version 9/09 35
- Slides: 35