Presentation is loading. Please wait.

Presentation is loading. Please wait.

© 2006 Pearson EducationMaking Objects 1 of 36 MAKING OBJECTS Views of a Class Defining Your Own Class Declaring Instance Variables Declaring Methods Sending.

Similar presentations


Presentation on theme: "© 2006 Pearson EducationMaking Objects 1 of 36 MAKING OBJECTS Views of a Class Defining Your Own Class Declaring Instance Variables Declaring Methods Sending."— Presentation transcript:

1 © 2006 Pearson EducationMaking Objects 1 of 36 MAKING OBJECTS Views of a Class Defining Your Own Class Declaring Instance Variables Declaring Methods Sending Messages

2 © 2006 Pearson EducationMaking Objects 2 of 36 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

3 © 2006 Pearson EducationMaking Objects 3 of 36 Specifications of the CSMobile A basic (ok, ridiculously simple) specification for 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 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 Let’s see...

4 © 2006 Pearson EducationMaking Objects 4 of 36 Simple Syntax for CSMobile Note: The point of this to show an outline of what a generic class looks like. Some functionality has been elided with // comments. /** * This class models a vehicle that * can move and turn. */ public class CSMobile { // declare class // declare instance variables private Engine _engine; private Door _driverDoor, _passengerDoor; private Wheel _frontDriverWheel, _rearDriverWheel, _frontPassengerWheel, _rearPassengerWheel; public CSMobile() { // 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 CSMobile

5 © 2006 Pearson EducationMaking Objects 5 of 36 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 } } // end of class CSMobile

6 © 2006 Pearson EducationMaking Objects 6 of 36 CSMobile Syntax Explained (1 of 5) /**... */ – 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 an instance of this class

7 © 2006 Pearson EducationMaking Objects 7 of 36 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 — determines what messages can be sent to this property

8 © 2006 Pearson EducationMaking Objects 8 of 36 CSMobile Syntax Explained (3 of 5) – name of instance variable is _engine Our coding convention: prefix all instance variables with an underscore, “_” private Door _driverDoor, _passengerDoor; – can declare multiple instance variables of the same type – just separate them with a comma _driverDoor and _passengerDoor are both instance variables of type Door public CSMobile() { – constructor for class CSMobile – remember: constructor is first message sent to instance – same identifier as its class – () makes it a method

9 © 2006 Pearson EducationMaking Objects 9 of 36 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 – most common use of constructors is to initialize instance variables i.e., construct initial state that’s just what we’re doing here! – note: Constructor CSMobile() refers directly to instance variable _engine all methods, including constructor, have direct access to all of their class’ instance variables – rest of instance variables are initialized in same way

10 © 2006 Pearson EducationMaking Objects 10 of 36 CSMobile Syntax Explained (5 of 5) public void moveForward() { –d–declares a method named moveForward –r–reserved word public i ndicates this method is to be part of class’ public interface thus any other object that knows about an instance of this class can send instance moveForward message –r–reserved word void indicates that this method does not return result when called some methods return values to calling method more on return types next lecture constructor declaration does not include return value –m–moveForward is name of method CS15 convention: method names should start with lowercase letter and all new words in method name should be capitalized –a–anything inside curly braces is part of method definition’s body

11 © 2006 Pearson EducationMaking Objects 11 of 36 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

12 © 2006 Pearson EducationMaking Objects 12 of 36 Object Relationships and Diagrams In our description, we said the CSMobile had an engine, doors, and wheels; these are components It can be said that the CSMobile is composed of its engine, doors, and wheels Containment is one way of associating 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? slideExamples.Car. Engine SlideExamples.Car.CSMo bile _engine

13 © 2006 Pearson EducationMaking Objects 13 of 36 In the City… Let’s say 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 ?

14 © 2006 Pearson EducationMaking Objects 14 of 36 The Association Relationship Answer: 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? slideExamples.Car.CSMobile _city SlideExamples.Car.City

15 © 2006 Pearson EducationMaking Objects 15 of 36 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 – the actual color of the CSMobile is an attribute, but it is also an instance of the 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 SlideExamples.Car.CSMobile Color _color

16 © 2006 Pearson EducationMaking Objects 16 of 36 CSMobile Class Box Used to document an individual class schematically – rectangle represents class (you might use an index card instead), labeled with its name at the top – next section shows properties of class (instance variable name optional) – finally show capabilities of class note that constructor is assumed don’t need to show it under capabilities Example of class CSMobile with the added properties just discussed: Engine _engine Door _driverDoor, _passengerDoor Wheel _frontDriverWheel, _rearDriverWheel, _frontPassengerWheel, _rearPassengerWheel City _city Color _color moveForward moveBackward turnLeft turnRight

17 © 2006 Pearson EducationMaking Objects 17 of 36 Class Diagrams A class diagram shows how generic classes relate to other classes – rectangle represents class, much like the class box – important relationships are connected with lines – important properties have name with reference to class boxes representing their type – attributes have type and identifier (but don’t show references) CSMobile _city _engine Color _color moveForward moveBackward turnLeft turnRight City knows about Engine contains an Note: Properties and Capabilities of City and Engine have been elided for clarity Note: Door s and Wheel s have been elided for clarity

18 © 2006 Pearson EducationMaking Objects 18 of 36 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 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 – it means a non-existent memory address

19 © 2006 Pearson EducationMaking Objects 19 of 36 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 – 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! NullPointerException

20 © 2006 Pearson EducationMaking Objects 20 of 36 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

21 © 2006 Pearson EducationMaking Objects 21 of 36 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 executed _csMobile.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!

22 © 2006 Pearson EducationMaking Objects 22 of 36 this keyword (1 of 2) What if we want one method in a class to call another method in the same class? – let’s say we want the CSMobile to have a turnAround() method – will want the turnAround() method to call the CSMobile ’s 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” – current instance, this, is receiver of message – so what we’re really doing with this is having an instance send a message to itself

23 © 2006 Pearson EducationMaking Objects 23 of 36 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(); } – tells the current class to execute the code in its turnLeft() method – since calling your own methods is common, using this is optional – this.turnLeft () and turnLeft() do the same thing – using this makes it more clear public void turnAround() { turnLeft(); } Now that we’ve seen how to call methods, let’s do something with the CSMobile... may be shorter, but not as clear

24 © 2006 Pearson EducationMaking Objects 24 of 36 Example: Driving Around Town Given a “world” where the CSMobile moves only along the roads defined by a regular grid: – think of it as a simplified city map: The streets are all the same length and go only horizontally and vertically (also, they are all 2-way) – CSMobile can move forward in direction it is facing and can turn 90 degrees left or right – can move only one block at a time Get CSMobile to corner of A St. and Third Av. and back, given… these initial conditions: – CSMobile starts at corner of B St. and First Av. facing north A St. B St. First Av. Second Av. Third Av.

25 © 2006 Pearson EducationMaking Objects 25 of 36 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 – CSMobile can only turn in right angles – moves from intersection to intersection Understanding the problem – must move two blocks North and one block West to get to Third and A – must move two blocks South and one block East to get back to First and B Solution: Third Av. and A St.

26 © 2006 Pearson EducationMaking Objects 26 of 36 Example: Pseudocode You can describe how to complete this task at some level of detail in English; this is called “pseudocode” tell CSMobile to move forward one block tell CSMobile to turn left tell CSMobile to move forward one block tell CSMobile to turn left tell CSMobile to move forward one block tell CSMobile to turn left tell CSMobile to move forward one block Pseudocode is more detailed than the initial problem specification, but not as detailed as the code itself – multiple levels of pseudocode may be used – 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 Now that we’ve pseudocoded, let’s see the actual code...

27 © 2006 Pearson EducationMaking Objects 27 of 36 Code Reusability Is our pseudocode reusable? What happens if we want to go back? The CSMobile is not pointing in the same direction after the trip as it was in the beginning! – We have changed the state of the CSMobile – We should add a left turn at the end so that the CSMobile is pointing in the same direction as in the beginning: Third Av. and A St.

28 © 2006 Pearson EducationMaking Objects 28 of 36 Reusable Pseudocode Here’s our new pseudocode: tell CSMobile to move forward one block tell CSMobile to turn left tell CSMobile to move forward one block tell CSMobile to turn left tell CSMobile to move forward one block tell CSMobile to turn left tell CSMobile to move forward one block tell CSMobile to turn left The final left turn leaves the CSMobile facing in the original direction Always think about what effects a method has on the state of an object – Other parts of the code depend on correct execution – Hand simulate to be sure

29 © 2006 Pearson EducationMaking Objects 29 of 36 Syntax for Trip to Third and A /** * This class models the process of a CSMobile * driving from the corner of First Av and B St * to Third Av and A St and back. */ public class TripToThirdAndA { private CSMobile _csMobile; public TripToThirdAndA() { _csMobile = new CSMobile(); } public void takeTrip() { _csMobile.moveForward(); _csMobile.turnLeft(); _csMobile.moveForward(); _csMobile.turnLeft(); _csMobile.moveForward(); _csMobile.turnLeft(); _csMobile.moveForward(); _csMobile.turnLeft(); } } // class TripToThirdAndA

30 © 2006 Pearson EducationMaking Objects 30 of 36 Syntax for Application /** * This class exists to start everything up. */ public class TripApp extends wheels.users.Frame { private TripToThirdAndA _trip; public TripApp() { _trip = new TripToThirdAndA(); _trip.takeTrip(); } public static void main ( String[] argv ) { new TripApp(); } } // end of class TripApp

31 © 2006 Pearson EducationMaking Objects 31 of 36 TripToThirdAndA Syntax Explained Note name of class: – describes process that object models – a TripToThirdAndA – usually, you would have ability to drive to Third and A be a capability of CSMobile, but we haven’t yet learned how to extend functionality of existing class Basic rundown: – declares instance variable of type CSMobile – initializes CSMobile instance in constructor – calls methods on CSMobile instance in takeTrip method _csMobile.moveForward(); – message sent by instance of TripToThirdAndA – message sent to instance of CSMobile – TripToThirdAndA tells its contained CSMobile instance to move forward – all other method calls are similar!

32 © 2006 Pearson EducationMaking Objects 32 of 36 TripApp Syntax Explained Only purpose of app is to start everything up: // create the instance _trip = new TripToThirdAndA(); // call method on the instance _trip.takeTrip(); This instance, in turn, calls methods ( moveForward, turnLeft, etc.) on its contained _csMobile instance

33 © 2006 Pearson EducationMaking Objects 33 of 36 Steps of Execution What’s going on inside the JavaVM? _csMobile.moveForward();... takeTrip method ends, so control returns to TripToThirdAndA constructor TripToThirdAndA constructor ends, so control returns to TripApp constructor TripApp constructor ends, so mainline ends and so does the program Mainline instantiates TripApp TripApp _trip = new TripToThirdAndA(); _trip.takeTrip(); CSMobile is created and told to take a trip inside takeTrip()

34 © 2006 Pearson EducationMaking Objects 34 of 36 We’re Done! It’s that simple! Now you know how to create and use a class Next time: Customizing methods and the mysterious association relationship

35 © 2006 Pearson EducationMaking Objects 35 of 36


Download ppt "© 2006 Pearson EducationMaking Objects 1 of 36 MAKING OBJECTS Views of a Class Defining Your Own Class Declaring Instance Variables Declaring Methods Sending."

Similar presentations


Ads by Google