You are on page 1of 37

MAKING OBJECTS

Views of a Class Defining Your Own Class Declaring Instance Variables Declaring Methods Sending Messages

Making Objects

1 of 37

September 15, 2011

Example: The CS15Mobile


One of the perks of being a CS15 Head TA is that you get a car for the semester: the CS15Mobile! Adam, Ian, and Jessica are in charge of designing and making the CS15Mobile Being the object-oriented people that they are, they think of the CS15Mobile as an object with properties and capabilities They will create a class to model the CS15Mobile and then make an instance of that class

Making Objects

2 of 37

September 15, 2011

Specifications of the CS15Mobile


They come up with the following basic (ok, ridiculously simple) specification for the CS15Mobile:
it should have an engine and wheels to move it should have doors so people can get in and out it should be able to move forward and backward it should be able to turn left and right

What are the CS15Mobiles properties?


engine, wheels, doors

What are the CS15Mobiles capabilities?


move forward, move backward, turn left, turn right dont forget the constructor all objects have the ability to construct themselves (when sent a message to do so by another object)

What would this look like in Java?


remember, properties are represented by instance variables capabilities are represented by methods

Lets see...
Making Objects 3 of 37 September 15, 2011

Simple Syntax for CS15Mobile


Note: The point of this is to show an outline of what a generic class definition looks like. Some functionality has been elided with // comments.

Three parts to class definition: declaration, list of properties, list of capabilities


package Demos.Car;
declaration

/** * 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

Simple Syntax for CS15Mobile (cont.)


// declare and define methods public void moveForward() { // code to move CS15Mobile forward } public void moveBackward() { // code to move CS15Mobile backward } public void turnLeft() { // code to turn CS15Mobile left } public void turnRight() { // code to turn CS15Mobile right }

} // end of class CS15Mobile

Additional capabilities (methods)

Making Objects

5 of 37

September 15, 2011

CS15Mobile Syntax Explained (1 of 5)


package Demos.Car;
package keyword tells Java that this class should be part of a package in this case, package is Demos.Car

/* ... */
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)

comment at the top of slide 4 is called a header comment


appear at top of a class explain purpose of class

public class CS15Mobile {


declares that we are about to create a class named CS15Mobile

public indicates that any other object can create an


instance of this class

Making Objects

6 of 37

September 15, 2011

CS15Mobile Syntax Explained (2 of 5)


Everything associated with a class must appear within curly braces!
all instance variables and methods; no code may appear outside curly braces: {

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

remember, properties are objects themselves


every object must be an instance of some class the class of an instance variable is called its type which determines what messages can be sent to this property

Making Objects

7 of 37

September 15, 2011

CS15Mobile Syntax Explained (3 of 5)


name of instance variable is _engine
CS15 convention: prefix all instance variables with an underscore: _

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

September 15, 2011

CS15Mobile Syntax Explained (4 of 5)


_engine = new Engine();
reserved word new tells Java to create a new instance
equals sign, =, means variable on left side gets, or is assigned, value on right side so value of instance variable _engine will become a new instance of class Engine
i.e., _engine gets a new Engine note: the instance variables identifier could be any combination of characters, starting with _, e.g., _scotty, _stuff, etc.

the most common use of constructors is to initialize instance variables


i.e., construct its initial state thats just what were doing here!

note: Constructor CS15Mobile() refers directly to instance variable _engine


all methods, including constructor, have direct access to all of their class instance variables

the rest of the instance variables are initialized in the same way
9 of 37

Making Objects

September 15, 2011

CS15Mobile Syntax Explained (5 of 5)


public void moveForward() {
declares method named moveForward reserved word public indicates this method is part of the class public interface
thus, any other object that knows about an instance of this class can send that instance a moveForward message (call moveForward on that instance)

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

anything inside curly braces { } is part of method definitions body


10 of 37

Making Objects

September 15, 2011

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

September 15, 2011

Object Relationships and Diagrams


In our description, we said the CS15Mobile had an engine, doors, and wheels; these are its components. We say that the CS15Mobile is composed of its engine, doors, and wheels.

Containment is when one class is a component of another.


How do you determine containment?
class CS15Mobile has an instance variable of type Engine class CS15Mobile creates an instance of type Engine therefore, CS15Mobile contains an Engine

How do we diagram containment?


Demos.Car.CS15Mobile _engine class box for CS15Mobile class box for Engine Demos.Car.Engine

Diagramming covered further in lab


Making Objects 12 of 37 September 15, 2011

Pawtucket, City of Dreams

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?)

Therefore, City can call methods on


parks schools streets CS15Mobiles

But, this relationship is not symmetric!

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

The Association Relationship


Answer: Associate the CS15Mobile with its City How do you determine association relationship?
well add to class CS15Mobile an instance variable of type City since class CS15Mobile doesnt create an instance of type City, City will not be contained by CS15Mobile we say: class CS15Mobile knows about City tune in next time to see how to set up an association (knows about) relationship in Java

How do we diagram association?


Demos.Car.CS15Mobile _city Demos.Car.City

Making Objects

14 of 37

September 15, 2011

Attributes
The CS15Mobile has certain attributes
color, size, position, etc.

Attributes are properties that describe the CS15Mobile


well add to class CS15Mobile an instance variable of type Color CS15Mobile is described by its Color this is different from an is composed of relationship class CS15Mobile doesnt contain its Color, nor is it associated with it we say: Color is an attribute of class CS15Mobile class CS15Mobile may set its own Color, or another class may call a method on it to set its Color the actual color of the CS15Mobile is an attribute, but it is also an instance of the Color class all instance variables are instances!

How do we diagram an attribute?


Demos.Car.CS15Mobile Color _color

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

Example of class CS15Mobile with the added properties just discussed:

CS15Mobile Engine _engine Door _driverDoor, _passengerDoor Wheel _frontDriverWheel, _rearDriverWheel, _frontPassengerWheel, _rearPassengerWheel City _city Color _color moveForward moveBackward turnLeft turnRight

Making Objects

16 of 37

September 15, 2011

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: Doors and Wheels have been elided for clarity

Note: Properties and Capabilities of City and Engine have been elided for clarity
17 of 37 September 15, 2011

Making Objects

Packages and Accessing Classes


Like BouncingBall, CS15Mobile is in package Demos But unlike BouncingBall, it is in a different sub-package
so its qualified (complete) name is: Demos.Car.CS15Mobile qualified name of a class includes names of all packages it belongs to (e.g., Demos and its subpackage Car)

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

Working With Variables


Variables in Java are like variables in math
hold single reference to value that can vary over time but need to have a previously defined value to be used

Remember CS15Mobile? Creating an instance variable was done in two parts


1. declaration: private Engine _engine; 2. initialization: _engine = new Engine();

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

September 15, 2011

Uninitialized Variables and null


If you forget to give your variables initial values, Java VM will reward you with a runtime error in the form of a NullPointerException
runtime errors are problems that occur while your program is running i.e., your program compiled successfully, but it does not execute successfully for now, when runtime errors occur, your program is usually stopped by Java VM

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

September 15, 2011

Assigning Values to Variables


Assignment provides a way to change the value of variables

replaces current value of a variable with a new value example: _engine = new Engine(); we say: _engine gets a new instance of class Engine

As weve seen, equals sign (=) is Javas syntax for assignment

variable left side of equals gets value of right side not like equals in Math! (which denotes equality of left and right-hand sides)

Using = with new new calls the constructor of the class


constructor creates a new instance of class new instance is value assigned to variable

Using = without new


assigns from one value to another ex: _exteriorColor = _interiorColor; makes the exterior color have the same value as the interior color

= is NOT commutative!

_exteriorColor = _interiorColor is not the same as _interiorColor = _exteriorColor


21 of 37 September 15, 2011

Making Objects

Assigning Values to Variables (Contd)


Note: Java copies the reference to the instance even if _exteriorColor instance is changed (points to a different memory address) at a later time, _interiorColor will still point to the old instance in its original location

private Color _exteriorColor;

null
private Color _interiorColor; _interiorColor = new Blue();
Instance of Blue

_exteriorColor = _interiorColor; _exteriorColor = new Green();


Instance of Green

Making Objects

22 of 37

September 15, 2011

Working With Methods


We know how to declare methods, but how do we call them? How can we send messages between objects? Syntax is: <variableName>.<methodName>();
public class City { private CS15Mobile _15mobile; public City() { _15mobile = new CS15Mobile(); _15mobile.moveForward(); }

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

In order for current instance to be receiver of message, we need a way to refer to it

Reserved word this is shorthand for this instance


this allows an instance to send a message to itself

Making Objects

24 of 37

September 15, 2011

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

Example: Driving Around Providence


Imagine a world where the CS15Mobile moves only along the roads defined by a regular grid:
simplified city map: the streets of Providence are all the same length and go only horizontally and vertically (also, they are all 2-way) CS15Mobile can move forward in the direction that it is facing and can turn 90 degrees left or right can move only one block at a time

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

September 15, 2011

Example: Analyzing the Problem


Most important first step is to analyze and understand the problem
ask questions about specifications of problem restate nature of problem in your own words

Understanding the specifications


only horizontal and vertical movement is allowed CS15Mobile can only turn at right angles moves from intersection to intersection

Understanding the problem


must move two blocks north and one block west to get to Thayer and Euclid must move two blocks south and one block east to get back to Brook and Waterman

Solution:

Making Objects

27 of 37

September 15, 2011

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

September 15, 2011

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

September 15, 2011

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

Syntax for Trip to Tedeschi


/** * This class models the process of a CS15Mobile * driving from the corner of Brook and Waterman * to Tedeschi(at Thayer and Euclid) and back. */ public class TripToTedeschi { private Demos.Car.CS15Mobile _15mobile; public TripToTedeschi() { _15mobile = new Demos.Car.CS15Mobile(); } public void takeTrip() { _15mobile.moveForward(); _15mobile.moveForward(); _15mobile.turnLeft(); _15mobile.moveForward(); _15mobile.turnLeft(); _15mobile.moveForward(); _15mobile.moveForward(); _15mobile.turnLeft(); _15mobile.moveForward(); _15mobile.turnLeft(); } } // end of class TripToTedeschi

Making Objects

31 of 37

September 15, 2011

Syntax for Application


/** * This class exists to start everything up. */ public class TripApp extends javax.swing.JFrame { private TripToTedeschi _trip; public TripApp() { _trip = new TripToTedeschi(); _trip.takeTrip(); } // mainline - you dont need to understand yet! public static void main ( String[] argv ) { new TripApp(); } } // end of class TripApp

Making Objects

32 of 37

September 15, 2011

TripToTedeschi Syntax Explained


Note that the name of TripToTedeschi class:
describes the process that the object models, a trip to Tedeschi usually, the ability to drive to Tedeschi would be a capability of CS15Mobile, but we havent yet learned how to extend functionality of existing classes

Basic rundown of code:


it declares an instance variable of type CS15Mobile it initializes the CS15Mobile instance in constructor it calls methods on the CS15Mobile instance in the takeTrip method

_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

September 15, 2011

TripApp Syntax Explained


Only purpose of TripApp is to start everything up:
// create the instance _trip = new TripToTedeschi(); // call method on the instance _trip.takeTrip();

This method, in turn, calls methods (moveForward, turnLeft, etc.) on the _15mobile instance that is contained by _trip.

Making Objects

34 of 37

September 15, 2011

Steps of Execution
Whats going on inside the JavaVM?
Mainline instantiates TripApp TripApp CS15Mobile is created and told to take a trip

_trip = new TripToTedeschi(); _trip.takeTrip();

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

September 15, 2011

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

You might also like