CS 170 Java Programming 1 Week 12: Creating Your Own Types
What s the Plan? Topic 1: A Little Review Work with loops to process arrays Write functions to process 2D Arrays in various ways Topic 2: Creating Your Own Types How to define instance variables to hold state How to define accessors to retrieve state information How to define mutators to modify objects How to read UML diagrams and class specifications How to use constructors to initialize an object's state
Your "IC" or "Lab" Document Use Word or OpenOffice to create a new document Save the file as IC012.doc (Office 97-2003 compatible) Place on your network U: drive or on a thumb drive Put your name and today's date at the top of the sheet Title it "CS 170 Lab Exercises Week 12" Start DrJava and we'll review a few basic concepts working with object arrays and 2D arrays
Review: 2D Arrays Create a 2D array with 2 sets of brackets int[][] grid= new int[2][4]; Each element in grid is a 4-element int[]
Using 2D Elements Address each element using two subscripts grid[1][3] = 30; First subscript is the row, second is the column Process 2D arrays using nestedfor loops final int ROWS = a.length; final int COLS = a[0].length; for (int r = 0; r < ROWS; r++) for (int c = 0; c = COLS; c++) // process a[r][c] here
Review: 2D Arrays and Methods You can process 2D arrays with methods several ways Exercise 12.1: open 2DArrayPractice in Week 12 Write a method named average() that averages all the elements in its 2D array parameter Exercise 12.2: processing a single row of a 2D array Write another average method that takes a 1D array Pass it the second row of values Exercise 12.3: how do you process a column? Can't pass a single variable; pass 2D var and int col Write a third average method that averages 2 column
Review: Modifying Images Let's apply 2D processing to images Open MediaPixels.java, compile and run Now, let's scramble the picture Put your code in the modifypic() method Grab the pixels from your image Exchange the pixels from the upper-left quadrant with those from the lower-right quadrant Pass the resulting pixels to show Exercise 12.4: shoot a screen-shot
Topic 2 Creating Your Own Types
Defining New Types Object-Oriented programming is extensible That means you aren't limited to the primitive types You don't have to ask Sun to create new object types Defining new types is the heart of OO programming Skills you ll need to define your own classes: Know how to define instance variables Know how to write constructors Know how to write accessor methods Know how to write mutator methods Know how to use static members 9
Review: What Are Classes? A pattern or blueprint that describes the common characteristics of a category of objects Classes Objects To make a SmallCar Parts: 4 Wheels 1 Body 1 Small Engine 4 Seats A Small Car Can Go Slow Stop Turn 10
The Class Definition The class definition specifies two kinds of things: Attributes: what "parts" are needed (doors, wheels, etc.) Behavior: how does the car perform (methods) Use the class definition to to create instances or or objects
Getting Started We'll write classes to complete a Pong game Choose Project->Open and locate Pong.drjava file 12
Compile and Run Choose Compile Project and Run Project to run Project facility allows you to work with related classes I usually put all project files in their own directory With Pong, pressing "B" should start the ball bouncing A-Z controls the left paddle, while K-M controls the right Nothing works! Your job is to write missing classes PongBall, PongScore and PongPaddle
The PongBall Class The PongBall class represents the ball in the game The Pong class uses the PongBall class The Pong game first creates a PongBall object It then calls the ball's move() method repeatedly After calling move() it calls getx() and gety() to find out where the ball is located. If it looks like the ball would "hit the wall", then the Pong program calls either bouncex() or bouncey() to cause the ball to change direction These are the methods that you have to write 14
The UML Diagram Here s the UML class diagram for the PongBall class UML Unified Modeling Language: Standard OO diagramming tool (like blueprints in construction) 4 data attributes One constructor Two accessors Three mutators 15
Implementation Existing project has a "dummy" PongBall class Defined in the PongLib.jar JAR file Can see this by looking at Project->Properties We'll replace this with a working version Exercise 12.5 Create a new class named PongBall Try to compile your project and shoot a screen-shot Does not compile because it doesn't have all the features that it needs Can right-click PongBall.java and Compile File 16
PongBall Data Four data attributes represent ball s state x and y represent the ball s position xvelocity and yvelocity represent the velocity of the ball in both the x and y directions A negative xvelocity means ball is moving right to left Implement attributes by defining instance variables 17
Defining Instance Variables Instance variables or fields hold object data Defined outside of any method, but inside class Can be used inside any method in the class private type name [ = initial-value ]; Modifier will almost always be the keyword private Don't want variable used outside of class 18
Pong Instance Variables Exercise 12.6: add instance variables (fields) for each item I usually start with a comment, but not required for style 19
Mutator Methods Some methods modify the object These are called mutator methods How do you tell if a method is a mutator? void return type In PongBall, those are: move(), bouncex(), and bouncey() 20
Implementing Mutators Step 1: Write the empty methods (stubs or public interface) Access specifier : public for methods Return type : mutator methods are always void Names : move(), bouncex(), and bouncey() Parameters: none for these, but still need () Place braces around empty bodies Now, we have skeletons, but what should they do? Have to consult detailed specification provided by designer Open PongGameSpec.pdf to see details 21
Commenting the Interface Specification represents contract your class should fulfill and provides information you need to implement behavior For each method, add documentation by adding special Javadoc comments that describe: A single sentence that describes what it does What each of the parameters (if any) mean What values the method returns 22
Completing the Mutators Mutators always modify the state of the object move() adds velocity to appropriate coordinate bouncex(), bouncey() change the sign of the velocity Exercise 12.7: compile, snap pic of completed mutators 23
Accessor Methods Some methods return information about an object These kinds of methods are called accessors Accessors are value-producing methods like functions Accessors have a return type other than void And end with a return expression public rettype accessorname() { // statements return rettype-expression; }
PongBall Accessors PongBall has two accessors, getx(), gety() Step 1: Let's write the Javadoc comments first See the specification document for the info you need Add an @return tag for every value-producing method 25
Implementing Accessors Step 2: Write the heading Access specifier : make these methods public Return type: accessors are nevervoid Names: getx() and gety() Parameters: none for these methods, but need () Step 3: Write the code in the body Exercise 12.8: compile, snap pic of completed accessors 10/19/2010 CS 170 - Week 12 26
Initializing PongBall Instance variables are automatically initialized Given values 0, false, or null depending on type Normally want to explicitly initialize your objects Pong expects to place the ball in center of the screen Note that there are no mutator methods that allow a client (the Pong class) to set the values for x and y This is done by writing a constructor 27
What Are Constructors? Constructors are defined inside a class like a method But, they are not called directly like a method Instead, called when you use the new operator Java uses the constructor to initialize your object A constructor is like a factory that creates an object. It is responsible for initializing an object s fields when the object is created. 28
Constructor Syntax Constructors look like methods, with two constraints: The name is always the same as the class The constructor cannot have a return type 29
Constructor Interface Step 1: Write the header Access specifier : is always public Return type : constructors never have a return type Names : the same as the class: PongBall Parameters: one for each field we need to initialize Supply both the type and a name for each variable 30
Constructor Javadoc Step 2: Document the constructor Use one @param tag for each parameter Separate name with space, end with a period 31
Constructor Implementation Step 3: Initialize each of the instance variables Assign the actual parameters to the fields Check carefully; make sure not to accidentally reverse 32
Testing and Using Your Class Shouldn't really just run Pong to test the class Don t really know how the Pong class uses it You ll need to write independent unit tests For right now, you can use the tests that I've written Next week, you'll write your own To run, compile your project and run Press "B" and your ball should start bouncing Exercise 12.9: snap pic of ball bouncing 33
Finishing Up To complete your IC "lab" document: Complete Exercise 12.10 in the Defining Fields lesson, Exercise 12.11 in the Defining Methods lesson, Exercise 12.13 in the Encapsulation lesson and Exercise 12.14 in the Constructors lesson Submit to Blackboard when done Reading for this week: Gaddis: Gaddis Chapter 6 A First Look at Classes
Homework and Quiz Homework, Quiz and Assignments Deadline is Monday at noon Three homework problems PongScore and PongPaddle The MyEmployee class Upload to Assignment Dropbox, be sure to press Submit Proficiency Makeup Next Week Proficiency Exam for classes after Thanksgiving