+ All Categories
Home > Documents > © 2006 Pearson Education Making Objects 1 of 19 MAKING OBJECTS Views of a Class Defining Your Own...

© 2006 Pearson Education Making Objects 1 of 19 MAKING OBJECTS Views of a Class Defining Your Own...

Date post: 22-Dec-2015
Category:
View: 217 times
Download: 2 times
Share this document with a friend
Popular Tags:
23
© 2006 Pearson Education Making Objects 1 of 19 MAKING OBJECTS • Views of a Class • Defining Your Own Class • Declaring Instance Variables • Declaring Methods • Sending Messages
Transcript
Page 1: © 2006 Pearson Education Making Objects 1 of 19 MAKING OBJECTS Views of a Class Defining Your Own Class Declaring Instance Variables Declaring Methods.

© 2006 Pearson EducationMaking Objects 1 of 19

MAKING OBJECTS

• Views of a Class

• Defining Your Own Class

• Declaring Instance Variables

• Declaring Methods

• Sending Messages

Page 2: © 2006 Pearson Education Making Objects 1 of 19 MAKING OBJECTS Views of a Class Defining Your Own Class Declaring Instance Variables Declaring Methods.

© 2006 Pearson EducationMaking Objects 2 of 19

Example: The CSMobile

• How can we best design and build the CSMobile?

• Think object-oriented: the CSMobile is an object with properties and capabilities

• Create a class to model the CSMobile and then make instances of that class

Page 3: © 2006 Pearson Education Making Objects 1 of 19 MAKING OBJECTS Views of a Class Defining Your Own Class Declaring Instance Variables Declaring Methods.

© 2006 Pearson EducationMaking Objects 3 of 19

Specifications of the CSMobile

• A basic (ok, ridiculously simple) specification of the CSMobile:

The CSMobile should have an engine and wheels so that it can move around. It also should have doors so that people can get in and out. The CSMobile should have the ability to move forward and backward. It should also be able to turn left and right.

• What are the CSMobile’s properties?– engine, wheels, doors

• What are the CSMobile’s capabilities?– move forward, move backward, turn left, turn right– don’t forget the constructor — all objects have the ability to be

constructed (when sent a message to do so by another object)

• What does this look like in Java?– remember, properties are represented by instance variables– capabilities are represented by methods

• Let’s see...

Page 4: © 2006 Pearson Education Making Objects 1 of 19 MAKING OBJECTS Views of a Class Defining Your Own Class Declaring Instance Variables Declaring Methods.

© 2006 Pearson EducationMaking Objects 4 of 19

Simple Syntax for CSMobileNote: The point of this to show an outline of what a generic class looks like. Some

functionality has been elided with // comments.

package demos.car;

/** Models a vehicle that can move and turn. */public class CSMobile {

// instance variables   private Engine engine; private Door driverDoor;private Door passengerDoor;

private Wheel frontDriverWheel; private Wheel rearDriverWheel; private Wheel frontPassengerWheel; private Wheel rearPassengerWheel;

public CSMobile() { // 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();}

avd
remember the distinction between declaring (first line) and the body, which is defining. so class and constructor really need two comments each
Page 5: © 2006 Pearson Education Making Objects 1 of 19 MAKING OBJECTS Views of a Class Defining Your Own Class Declaring Instance Variables Declaring Methods.

© 2006 Pearson EducationMaking Objects 5 of 19

Simple Syntax for CSMobile (cont.)

// declare and define methods

public void moveForward() { // code to move CSMobile forward}

public void moveBackward() { // code to move CSMobile backward}

public void turnLeft() { // code to turn CSMobile left}

public void turnRight() { // code to turn CSMobile right}

}

Page 6: © 2006 Pearson Education Making Objects 1 of 19 MAKING OBJECTS Views of a Class Defining Your Own Class Declaring Instance Variables Declaring Methods.

© 2006 Pearson EducationMaking Objects 6 of 19

CSMobile 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• compiler ignores comments• but we comment for people who want to read our code

– class CSMobile has a kind of block comment called a header comment• appears at top of class• explains purpose of class

public class CSMobile {– declares that we are about to create a class named CSMobile– public indicates that any other object can create instance of this class

Page 7: © 2006 Pearson Education Making Objects 1 of 19 MAKING OBJECTS Views of a Class Defining Your Own Class Declaring Instance Variables Declaring Methods.

© 2006 Pearson EducationMaking Objects 7 of 19

CSMobile Syntax Explained (2 of 5)

• Everything associated with class must appear within the curly braces, the body{ //all instance variables and methods;

} // no code may appear outside braces

// ...– everything on the same line after // is a comment– known as 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• CSMobile “encapsulates” its engine

– remember, properties are objects themselves• every object must be an instance of some class• class of instance variable is called its type

– type determines what messages this property understands

Page 8: © 2006 Pearson Education Making Objects 1 of 19 MAKING OBJECTS Views of a Class Defining Your Own Class Declaring Instance Variables Declaring Methods.

© 2006 Pearson EducationMaking Objects 8 of 19

CSMobile Syntax Explained (3 of 5)

– name of instance variable is engine• Note: We don’t follow the book’s coding convention to prefix all instance

variables with an underscore, “_”

private Door driverDoor, private Door passengerDoor;

– Java allows to declare multiple instance variables of the same type and just separate them with a comma, but we recommend to declare each variable separately

– driverDoor and passengerDoor are instance variables of type Door

public CSMobile() {…}– constructor for class CSMobile– remember: constructor is first message sent to instance– must have the same identifier as its class– () makes it a method

• Standard convention: variable names start with lowercase letter and all new words in the name are capitalized

Page 9: © 2006 Pearson Education Making Objects 1 of 19 MAKING OBJECTS Views of a Class Defining Your Own Class Declaring Instance Variables Declaring Methods.

© 2006 Pearson EducationMaking Objects 9 of 19

CSMobile Syntax Explained (4 of 5)

engine = new Engine();

– reserved word new tells Java that you want to make a new instance

– equals sign, =, means variable on left side “gets” value of right side

– so value of instance variable engine will be new instance of class Engine• i.e., engine “gets” a new Engine

– constructors initialize the new instance• i.e., construct initial state

– note: Constructor CSMobile() refers directly to engine• all methods, including constructor, have direct access to all of their class’

instance variables

– all other instance variables are initialized in the same way

Page 10: © 2006 Pearson Education Making Objects 1 of 19 MAKING OBJECTS Views of a Class Defining Your Own Class Declaring Instance Variables Declaring Methods.

© 2006 Pearson EducationMaking Objects 10 of 19

Another way to initialize CSMobile

• Variables can be initialized there where they are declared

• Consider our CSMobile:

package demos.car;

/** Models a vehicle that can move and turn. */public class CSMobile {

// instance variables   private Engine engine = new Engine(); private Door driverDoor = new Door(); private Door passengerDoor = new Door(); private Wheel frontDriverWheel = new Wheel(); private Wheel rearDriverWheel = new Wheel(); private Wheel frontPassengerWheel = new Wheel(); private Wheel rearPassengerWheel = new Wheel();

public CSMobile() {}

• Advantages of the latter form: – uninitialized variables are often cause of errors,

• giving them a value right away is a good practice (see later)! – the code is shorter, more readable– empty constructor can be omitted (Java inserts one)

avd
remember the distinction between declaring (first line) and the body, which is defining. so class and constructor really need two comments each
Page 11: © 2006 Pearson Education Making Objects 1 of 19 MAKING OBJECTS Views of a Class Defining Your Own Class Declaring Instance Variables Declaring Methods.

© 2006 Pearson EducationMaking Objects 11 of 19

CSMobile Syntax Explained (5 of 5)

public void moveForward() {…}

– declares a method named moveForward

– reserved word public indicates this method is visible to anyone• any other object that knows an instance of this class can send it moveForward message

– reserved word void means that this method does not return any result• some methods return values to calling method• later we will learn more about return types• constructor declaration does not need to state return value, it returns the

new object instance

– moveForward is name of the method

– anything inside curly braces is part of method definition’s body

• Standard convention: method names start with lowercase letter and all new words in the name are capitalized

Page 12: © 2006 Pearson Education Making Objects 1 of 19 MAKING OBJECTS Views of a Class Defining Your Own Class Declaring Instance Variables Declaring Methods.

© 2006 Pearson EducationMaking Objects 12 of 19

CSMobile

• That’s it for the basic skeleton of class CSMobile!

• Now you know how to write a class with properties and capabilities– can declare variables and methods

• By the end of the course, you will be able to write the full CSMobile class!– will be able to fully define methods– will add a few more instance variables and change methods a little– but... basic structure will be the same!

• Next we look at representation of our three types of properties– components– associations with other objects– attributes

Page 13: © 2006 Pearson Education Making Objects 1 of 19 MAKING OBJECTS Views of a Class Defining Your Own Class Declaring Instance Variables Declaring Methods.

© 2006 Pearson EducationMaking Objects 13 of 19

Object Relationships and Diagrams

• Our specification says that CSMobile has an engine, doors, and wheels; these are components

• We can say that the CSMobile is composed of its engine, doors, and wheels

• Containment is a way to associate objects with one another

• How do you determine containment?– class CSMobile has an instance variable of type Engine– class CSMobile creates an instance of type Engine– therefore, CSMobile is composed of an Engine

• How do we diagram containment?

CSMobileengine

Engine

avd
disagree w/ how you determine containment. remember you also have an ivar for color and you new it, so there's no distinction between them as far as java is concerned. it is a modeling difference, in the eye of the beholder/modeler. attributes are likely to change, components not, and the latter are sub-0bjects obeying a "is composed of" relationship. attributes are kinda like "is described by"
Page 14: © 2006 Pearson Education Making Objects 1 of 19 MAKING OBJECTS Views of a Class Defining Your Own Class Declaring Instance Variables Declaring Methods.

© 2006 Pearson EducationMaking Objects 14 of 19

In the City…

• Suppose we have a City object.

• City contains and therefore constructs– parks– schools– streets– cars, e.g., CSMobiles (hey, why not?)

• Therefore, City can call methods on – parks– schools– streets– CSMobiles

• But, relationship is not symmetric!

• Park, School, Street and CSMobile classes don’t automatically have access to City -- i.e., they can’t call methods on City

• How can we provide CSMobile with access to City?

Page 15: © 2006 Pearson Education Making Objects 1 of 19 MAKING OBJECTS Views of a Class Defining Your Own Class Declaring Instance Variables Declaring Methods.

© 2006 Pearson EducationMaking Objects 15 of 19

The Association Relationship

• Answer: We associate the CSMobile with its City

• How do you determine the association relationship?– we’ll add to class CSMobile an instance variable of type City– class CSMobile doesn’t create its instance of type City; therefore, City won’t be a component of CSMobile

– we say: class CSMobile “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?

CSMobile city City

Page 16: © 2006 Pearson Education Making Objects 1 of 19 MAKING OBJECTS Views of a Class Defining Your Own Class Declaring Instance Variables Declaring Methods.

© 2006 Pearson EducationMaking Objects 16 of 19

Attributes

• The CSMobile has certain attributes– color, size, position, etc.

• Attributes are properties that describe the CSMobile– we’ll add to class CSMobile an instance variable of type Color– CSMobile is described by its Color– different than “is composed of” relationship– class CSMobile doesn’t contain its Color, nor is it associated with it– we say: Color is an attribute of class CSMobile– class CSMobile may set its own Color or another class may call a method on it

to set its Color– actual color of CSMobile is an attribute, and it is also instance of Color class

• all instance variables are instances!

• How do we diagram an attribute?

– because attributes don’t have the full weight of other object relationships, we just put their type and name in line, without an arrow for the reference

CSMobile

Color color

Page 17: © 2006 Pearson Education Making Objects 1 of 19 MAKING OBJECTS Views of a Class Defining Your Own Class Declaring Instance Variables Declaring Methods.

© 2006 Pearson EducationMaking Objects 17 of 19

Class Box

• Used to depict schematically a class– rectangle for a class (like index card) with name of class at the top– properties of class in next section (types, names of instance variables)– capabilities of class in bottom section

• note: constructor can be assumed

• Example of class CSMobile with the properties discussed:

CSMobile

Engine engineDoor driverDoorDoor passengerDoorWheel frontDriverWheelWheel rearDriverWheelWheel frontPassengerWheelWheel rearPassengerWheelCity cityColor color

moveForward()moveBackward()turnLeft()turnRight()

Page 18: © 2006 Pearson Education Making Objects 1 of 19 MAKING OBJECTS Views of a Class Defining Your Own Class Declaring Instance Variables Declaring Methods.

© 2006 Pearson EducationMaking Objects 18 of 19

Class Diagrams

• A class diagram shows how classes relate to other classes– rectangle represents class as class box– important relationships are connected by lines with arrows– important properties have name on top of the lines – attributes have type and identifier (but don’t show references)

City

<<knows about>>

Engine

<<contains an>>

Note: Properties and capabilities of City and Engine have been elided for clarity

city

engine

CSMobile

Color color

moveForward()

moveBackward()turnLeft()turnRight()

avd
you said nothing about attributes and how they differ from components and all of a sudden we have "knows about" w/o any explanation. At least say that it is an "association" relationship and we'll learn more about it in next lecture.
Page 19: © 2006 Pearson Education Making Objects 1 of 19 MAKING OBJECTS Views of a Class Defining Your Own Class Declaring Instance Variables Declaring Methods.

© 2006 Pearson EducationMaking Objects 19 of 19

Packages and Accessing Classes

• Like BouncingBall, CSMobile is in package demos

• But unlike BouncingBall, it is in a different sub-package– so its qualified name is: demos.car.CSMobile– the qualified name of a class includes the names of all the packages it

belongs to (e.g., demos and its sub-package car)

• To access a class, you can refer to it by its qualified name

• You don’t need to qualify class in same package as current class, or a class that is imported– Engine is in package demos.car– declaration package demos.car; at the top of CSMobile class

definition makes CSMobile part of demos.car package– thus CSMobile can refer to demos.car.Engine as, simply, Engine

• Similarly, you don’t need to qualify an imported class – import wheels.users.Frame; can occur after package declaration– then CSMobile can use simply Frame

Page 20: © 2006 Pearson Education Making Objects 1 of 19 MAKING OBJECTS Views of a Class Defining Your Own Class Declaring Instance Variables Declaring Methods.

© 2006 Pearson EducationMaking Objects 20 of 19

Working With Variables

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

• Remember CSMobile? Creating an instance variable was done in two parts1. 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– it means a non-existent memory address

Page 21: © 2006 Pearson Education Making Objects 1 of 19 MAKING OBJECTS Views of a Class Defining Your Own Class Declaring Instance Variables Declaring Methods.

© 2006 Pearson EducationMaking Objects 21 of 19

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

object’s instance variables!– most common occurrence of a NullPointerException is trying to

send a message to an uninitialized variable

WATCH OUT!

Page 22: © 2006 Pearson Education Making Objects 1 of 19 MAKING OBJECTS Views of a Class Defining Your Own Class Declaring Instance Variables Declaring Methods.

© 2006 Pearson EducationMaking Objects 22 of 19

Assigning Values to Variables• Assignment provides a way to change the value of variables

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

• As we’ve seen, equals sign, =, is Java’s syntax for assignment– variable on 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– calls the constructor of the class– constructor results in 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

Page 23: © 2006 Pearson Education Making Objects 1 of 19 MAKING OBJECTS Views of a Class Defining Your Own Class Declaring Instance Variables Declaring Methods.

© 2006 Pearson EducationMaking Objects 23 of 19

Working With Methods

• We know how to declare methods, but how do we call them? How can we send messages between objects?

• Syntax is variableIdentifier.methodIdentifier();public class City {

private CSMobile csMobile;

public City() { csMobile = new CSMobile(); csMobile.moveForward();

}

}

• Sending a message (“calling moveForward on csMobile”) causes code associated with method to be executedcsMobile.moveForward() is a method call

• csMobile is message’s receiver (one being told to move)• dot (“.”) separates receiver from message name• moveForward is name of message to be sent• () denotes parameters to the message• more on parameters next lecture! woo hoo!


Recommended