CS 170 Java Programming 1. Week 12: Creating Your Own Types

Similar documents
Express Yourself. Writing Your Own Classes

CS 170 Java Programming 1. Week 13: Classes, Testing, Debugging

CS 170 Java Programming 1. Week 5: Procedures and Functions

CS 170 Java Programming 1. Week 9: Learning about Loops

CS 170 Java Programming 1. Week 10: Loops and Arrays

Week 2: Data and Output

CS 170 Java Programming 1. Week 15: Interfaces and Exceptions

Week 3: Objects, Input and Processing

Object-Oriented Language Development Company

Structured Programming

CS 170 Java Programming 1. Week 7: More on Logic

Slide 1 CS 170 Java Programming 1

ICS 61 Game Systems and Design Introduction to Scratch

Slide 1 CS 170 Java Programming 1 Multidimensional Arrays Duration: 00:00:39 Advance mode: Auto

Tips from the experts: How to waste a lot of time on this assignment

Com S 227 Spring 2018 Assignment points Due Date: Thursday, September 27, 11:59 pm (midnight) "Late" deadline: Friday, September 28, 11:59 pm

Homework Assignment: Sudoku Board

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

Our second exam is Monday, April 3. Note that it will not be possible to get all the homework submissions graded before the exam.

Slide 1 CS 170 Java Programming 1 Testing Karel

Creating an object Instance variables

CS112 Lecture: Defining Instantiable Classes

EECS168 Exam 3 Review

Express Yourself. What is Eclipse?

CS11 Introduction to C++ Fall Lecture 1

Tips from the experts: How to waste a lot of time on this assignment

CS 251 Intermediate Programming Methods and Classes

CS 251 Intermediate Programming Methods and More

CS1004: Intro to CS in Java, Spring 2005

CS111: PROGRAMMING LANGUAGE II. Lecture 1: Introduction to classes

AP Computer Science Chapter 10 Implementing and Using Classes Study Guide

Computer Science II. OO Programming Classes Scott C Johnson Rochester Institute of Technology

Tips from the experts: How to waste a lot of time on this assignment

Note: This is a miniassignment and the grading is automated. If you do not submit it correctly, you will receive at most half credit.

CS112 Lecture: Defining Classes. 1. To describe the process of defining an instantiable class

Our second exam is Thursday, November 10. Note that it will not be possible to get all the homework submissions graded before the exam.

Defining Classes and Methods

CS Week 14. Jim Williams, PhD

CS 170 Java Tools. Step 1: Got Java?

12/22/11. Java How to Program, 9/e. public must be stored in a file that has the same name as the class and ends with the.java file-name extension.

Documentation Requirements Computer Science 2334 Spring 2016

Guessing Game with Objects

A A B U n i v e r s i t y

CS/ENGRD 2110 FALL Lecture 2: Objects and classes in Java

Final Exam. Programming Assignment 3. University of British Columbia CPSC 111, Intro to Computation Alan J. Hu. Readings

CSE115 Introduction to Computer Science I Coding Exercise #7 Retrospective Fall 2017

CS 315 Software Design Homework 3 Preconditions, Postconditions, Invariants Due: Sept. 29, 11:30 PM

Final Exam. Programming Assignment 3. University of British Columbia CPSC 111, Intro to Computation Alan J. Hu. Readings

APCS Semester #1 Final Exam Practice Problems

CS Exam 1 Review Suggestions

CS18000: Programming I

Exam 1 - (20 points)

CS11 Intro C++ Spring 2018 Lecture 3

CSSE 220 Day 3. Check out UnitTesting and WordGames from SVN

Express Yourself. The Great Divide

CSCI 200 Lab 3 Using and implementing sets

CSE 142 Su 02 Homework 4

9/19/2018 Programming Data Structures. Polymorphism And Abstract

Recommended Group Brainstorm (NO computers during this time)

Chapter 4 Defining Classes I

Chapter 6 Lab Classes and Objects

Binghamton University. CS-140 Fall Problem Solving. Creating a class from scratch

Object-Oriented Programming Concepts

CS 170 Java Tools. Step 1: Got Java?

CS2102, D15 Exam 1. Name:

CS Homework 11 p. 1. CS Homework 11

INHERITANCE AND EXTENDING CLASSES

This course supports the assessment for Scripting and Programming Applications. The course covers 4 competencies and represents 4 competency units.

Java How to Program, 10/e. Copyright by Pearson Education, Inc. All Rights Reserved.

CS/ENGRD 2110 SPRING Lecture 2: Objects and classes in Java

CS 134 Programming Exercise 9:

Introduction to Programming System Design CSCI 455x (4 Units)

CSCI 200 Lab 1 Implementing and Testing Simple ADTs in Java

Creating Java Programs with Greenfoot

Tips from the experts: How to waste a lot of time on this assignment

Defining Classes and Methods. Objectives. Objectives 6/27/2014. Chapter 5

CS11 Intro C++ Spring 2018 Lecture 1

CS 201 Advanced Object-Oriented Programming Lab 5 - Sudoku, Part 1 Due: March 3/4, 11:30 PM

CS 132 Exam #1 - Study Suggestions

TeenCoder : Java Programming (ISBN )

Homework 2: Imperative Due: 5:00 PM, Feb 15, 2019

Problem 1: Building and testing your own linked indexed list

Inheritance and Interfaces

CSC207 Week 2. Larry Zhang

CSE 142/143 Unofficial Commenting Guide Eric Arendt, Alyssa Harding, Melissa Winstanley

CS 201 Advanced Object-Oriented Programming Lab 6 - Sudoku, Part 2 Due: March 10/11, 11:30 PM

Review sheet for Final Exam (List of objectives for this course)

Foundations, Reasoning About Algorithms, and Design By Contract CMPSC 122

CISC 1600, Lab 2.3: Processing animation, objects, and arrays

Week 7 - More Java! this stands for the calling object:

Objects and State. COMP1400 Week 9. Wednesday, 19 September 12

Object Oriented Design: Identifying Objects

CS161: Introduction to Computer Science Homework Assignment 10 Due: Monday 11/28 by 11:59pm

Chapter 6 Lab Classes and Objects

CS 241 Data Organization. August 21, 2018

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 3: SEP. 13TH INSTRUCTOR: JIAYIN WANG

CSCI Lab 9 Implementing and Using a Binary Search Tree (BST)

Mathematics/Science Department Kirkwood Community College. Course Syllabus. Computer Science CSC142 1/10

Comp Intermediate Programming EXAM #1 February 16, 2004 Rice University - Instructors: Cox & Nguyen

Final Exam CS 152, Computer Programming Fundamentals December 9, 2016

Transcription:

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