Professional Documents
Culture Documents
Views of a Class Defining Your Own Class Declaring Instance Variables Declaring Methods Sending Messages
Making Objects
1 of 37
Making Objects
2 of 37
Lets see...
Making Objects 3 of 37 September 15, 2011
/** * This class models a vehicle that * can move and turn. */ public class CS15Mobile { // declare class // start class definition by declaring // instance variables private Engine _engine; private Door _driverDoor, _passengerDoor; private Wheel _frontDriverWheel, _rearDriverWheel, _frontPassengerWheel, _rearPassengerWheel;
properties declaration (instance variables) constructor is a capability (method)
public CS15Mobile() { // declare constructor // construct the component objects _engine = new Engine(); _driverDoor = new Door(); _passengerDoor = new Door(); _frontDriverWheel = new Wheel(); _rearDriverWheel = new Wheel(); _frontPassengerWheel = new Wheel(); _rearPassengerWheel = new Wheel(); } // end constructor for CS15Mobile
4 of 37 September 15, 2011
Making Objects
Making Objects
5 of 37
/* ... */
everything between /* and */ is a block comment
useful for explaining specifics of classes the compiler ignores comments comment to make code more readable for ourselves (and TAs)
Making Objects
6 of 37
Inline Comments
everything on the same line after two forward slashes // is an inline comment describes important features in code
private Engine _engine; declares an instance variable named _engine of type Engine reserved word private
indicates that instance variable will be available only to methods within this class other objects do not have access to _engine thus, CS15Mobile encapsulates its _engine
Making Objects
7 of 37
private Door
_driverDoor, _passengerDoor;
we can declare multiple instance variables of the same type by separating them with commas _driverDoor and _passengerDoor are both instance variables of type Door NOTE: we havent given these instance variables any value yet!
public CS15Mobile() {
constructor for class CS15Mobile remember: constructor is first message sent to a newly created object must have the same identifier (name) as its class () makes it a method
Making Objects
8 of 37
the rest of the instance variables are initialized in the same way
9 of 37
Making Objects
reserved word void indicates that this method does not return a result when called
some methods return values to the object which called the method constructor declaration does not include return value (because constructors always return a new object instance!) more on return values next lecture
moveForward is name of method CS15 convention: method names start with lowercase
letter, and all following words in method name are capitalized
Making Objects
CS15Mobile
Thats it for basic skeleton of class CS15Mobile! Now you know how to write a class with properties (instance variables) and capabilities (methods). In a few weeks, you would be able to write the full CS15Mobile class!
you would be able to fully define methods you would add a few more instance variables and change methods a little but basic structure will be the same!
Next we look at the representation of objects three types of properties. These are:
components associations with other objects attributes
Making Objects
11 of 37
Lets say we have a (very self-aware) City object. City contains and therefore constructs
parks schools streets cars, e.g., CS15Mobiles (hey, why not?)
Park, School, Street and CS15Mobile classes dont automatically have access to City -- i.e., they cant call methods on City
Lets focus on our CS15Mobile: how can we provide CS15Mobile with access to City?
Making Objects 13 of 37 September 15, 2011
Making Objects
14 of 37
Attributes
The CS15Mobile has certain attributes
color, size, position, etc.
because attributes dont have full weight of other object relationships, in CS15 we list their type and name below class, without an arrow for reference
Making Objects 15 of 37 September 15, 2011
Class Box
A rectangle is drawn to represent an individual class schematically
at top is the class name next section lists properties of class (instance variable names are optional) below properties, names of class capabilities
note that constructor is assumed and is not listed under capabilities
CS15Mobile Engine _engine Door _driverDoor, _passengerDoor Wheel _frontDriverWheel, _rearDriverWheel, _frontPassengerWheel, _rearPassengerWheel City _city Color _color moveForward moveBackward turnLeft turnRight
Making Objects
16 of 37
Class Diagrams
A class diagram shows how classes relate to other classes (as shown briefly on slides 12 & 14)
rectangles represent classes relationships between classes are shown with lines Association and containment properties have their names with reference to class boxes representing their type attributes have type and identifier (but dont show references)
CS15Mobile _city _engine Color _color moveForward moveBackward turnLeft turnRight
knows about
City contains
Engine
Note: Properties and Capabilities of City and Engine have been elided for clarity
17 of 37 September 15, 2011
Making Objects
To access a class, you can always refer to it by its qualified name But if class you want to access is in same package as current class, you can omit the package name
Engine is in package Demos.Car package Demos.Car at the top of CS15Mobile class definition makes CS15Mobile part of the Demos.Car package therefore, CS15Mobile can refer to Demos.Car.Engine as, simply, Engine
Making Objects 18 of 37 September 15, 2011
What is value of _engine before step 2? What would happen if step 2 were omitted? Java gives all variables a default value of null
i.e., it has no useful value null is another reserved word in Java means a non-existent memory address
Making Objects
19 of 37
NullPointerException
if you get such an error, make sure you have initialized all of your objects instance variables! most common occurrence of a NullPointerException is trying to send a message to an uninitialized variable
WATCH OUT!
Making Objects
20 of 37
replaces current value of a variable with a new value example: _engine = new Engine(); we say: _engine gets a new instance of class Engine
variable left side of equals gets value of right side not like equals in Math! (which denotes equality of left and right-hand sides)
= is NOT commutative!
Making Objects
null
private Color _interiorColor; _interiorColor = new Blue();
Instance of Blue
Making Objects
22 of 37
Sending a message (calling moveForward on _15mobile) causes the methods code to be executed
_15mobile.moveForward(); is a method call _15mobile is the messages receiver (the instance being told to move) dot (.) separates receiver from method name moveForward is the name of message to be sent () denotes parameters sent to the message more on parameters next lecture! Yippee!
Making Objects 23 of 37 September 15, 2011
this keyword (1 of 2)
What if we want one method in a class to call another method in the same class?
say we want the CS15Mobile to have a turnAround() method want turnAround() method to call CS15Mobiles own turnLeft() or turnRight() method twice
Making Objects
24 of 37
this keyword (2 of 2)
Example of using this to call a method on the current instance of the class:
public void turnAround() { this.turnLeft(); this.turnLeft(); }
this.turnLeft(); tells current class to execute code in its turnLeft() method since calling your own methods is common, using this is optional but it makes your code clearer this.turnLeft() and turnLeft() do same thing
public void turnAround() { turnLeft(); turnLeft(); may be shorter, but not as clear }
Now that weve seen how to call methods, lets do something with CS15Mobile...
Making Objects 25 of 37 September 15, 2011
How do we get CS15Mobile to Tedeschi Food Shops (corner of Thayer and Euclid) and back, given:
CS15Mobile starts at corner of Brook and Waterman facing north (initial conditions)
Euclid Angell Waterman Thayer
Making Objects
26 of 37
Brook
Solution:
Making Objects
27 of 37
Example: Pseudocode
Describe how to complete task at some level of detail in English; this is called pseudocode
tell CS15Mobile to move forward one block tell CS15Mobile to move forward one block tell CS15Mobile to turn left tell CS15Mobile to move forward one block tell CS15Mobile to turn left tell CS15Mobile to move forward one block tell CS15Mobile to move forward one block tell CS15Mobile to turn left tell CS15Mobile to move forward one block
Pseudocode is more detailed than initial problem specification, but not as detailed as code itself
pseudocode is often used on multiple levels this decomposition process is called stepwise refinement because each successive level is more detailed or refined good programming flows from specification to pseudocode to actual code
Making Objects
28 of 37
Code Reusability
Is our pseudocode reusable? What happens if we want to make the trip again? Note that the CS15Mobile is not pointing in same direction after trip as it was in beginning!
we have changed state of CS15Mobile we should add a left turn at the end so that CS15Mobile is pointing in same direction as in beginning:
Making Objects
29 of 37
Reusable Pseudocode
Heres our new pseudocode:
tell CS15Mobile to move forward one block tell CS15Mobile to move forward one block tell CS15Mobile to turn left tell CS15Mobile to move forward one block tell CS15Mobile to turn left tell CS15Mobile to move forward one block tell CS15Mobile to move forward one block tell CS15Mobile to turn left tell CS15Mobile to move forward one block tell CS15Mobile to turn left
Final left turn leaves CS15Mobile facing in original direction Always think about what effects a method has on state of an object
other parts of code depend on correct execution use hand simulation to be sure (mentally step through each line and use hand to simulate code)
Now that weve written pseudocode, lets see the actual code...
Making Objects 30 of 37 September 15, 2011
Making Objects
31 of 37
Making Objects
32 of 37
_15mobile.moveForward();
message sent by the instance of TripToTedeschi message sent to the instance of CS15Mobile TripToTedeschi tells its contained CS15Mobile instance to move forward all other method calls are similar!
Making Objects
33 of 37
This method, in turn, calls methods (moveForward, turnLeft, etc.) on the _15mobile instance that is contained by _trip.
Making Objects
34 of 37
Steps of Execution
Whats going on inside the JavaVM?
Mainline instantiates TripApp TripApp CS15Mobile is created and told to take a trip
inside takeTrip()
_15mobile.moveForward(); _15mobile.moveForward(); . . .
takeTrip method ends, so control returns to TripToTedeschi constructor TripToTedeschi constructor ends, so control returns to TripApp constructor TripApp constructor ends, so mainline ends and so does the program
Making Objects 35 of 37 September 15, 2011
Were Done!
Its that simple! Now you know how to create and use a class Next time: Customizing methods and setting up associations between objects!
Making Objects
36 of 37
Announcements OBJECTS assignment is due at 10:00pm tomorrow (Friday, Sept 16th) in wooden handin bin CIT 2nd floor CLOCK is out! Design Questions are due September 17th at 10:pm. Code is due September 20th at 11:59pm. Textbook Reading Assignment: Table 2.1, 2.3.4, and 3.1-3.3 TA hours have started! TA Hours are held on the 2nd Floor of the CIT in the Fishbowl (CIT 271). If you still dont have a login, missed the first few lectures and want to take the course, or just have some questions, come talk to us. Thats what we are here for!
Making Objects 37 of 37 September 15, 2011