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

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

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

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 10: Loops and Arrays

Express Yourself. Writing Your Own Classes

Structured Programming

Week 2: Data and Output

Week 3: Objects, Input and Processing

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

CSE115 / CSE503 Introduction to Computer Science I. Dr. Carl Alphonce 343 Davis Hall Office hours:

JAVA MOCK TEST JAVA MOCK TEST II

Polymorphism: Inheritance Interfaces

Name: CSC143 Exam 1 1 CSC 143. Exam 1. Write also your name in the appropriate box of the scantron

CS 251 Intermediate Programming Inheritance

Week 9. Abstract Classes

CS 11 java track: lecture 3

CS Exam 1 Review Suggestions

Java Programming Lecture 7

Express Yourself. What is Eclipse?

Slide 1 CS 170 Java Programming 1

Creating Java Programs with Greenfoot

CSE 70 Final Exam Fall 2009

COMP-202 Unit 10: Basics of GUI Programming (Non examinable) (Caveat: Dan is not an expert in GUI programming, so don't take this for gospel :) )

STUDENT LESSON A20 Inheritance, Polymorphism, and Abstract Classes

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

University of British Columbia CPSC 111, Intro to Computation Jan-Apr 2006 Tamara Munzner

Chapter 14 Abstract Classes and Interfaces

INHERITANCE & POLYMORPHISM. INTRODUCTION IB DP Computer science Standard Level ICS3U. INTRODUCTION IB DP Computer science Standard Level ICS3U

Midterm assessment - MAKEUP Fall 2010

Using the API: Introductory Graphics Java Programming 1 Lesson 8

MIT AITI Swing Event Model Lecture 17

Interfaces & Polymorphism part 2: Collections, Comparators, and More fun with Java graphics

Throughout the exam, write concisely and underline key words or phrases. Have fun! Exam 2. Week 7 (Winter 2013). Dr. Yoder. Sec 031.

Abstract Classes. Abstract Classes a and Interfaces. Class Shape Hierarchy. Problem AND Requirements. Abstract Classes.

CSE 331 Software Design and Implementation. Lecture 19 GUI Events

DEMYSTIFYING PROGRAMMING: CHAPTER SIX METHODS (TOC DETAILED) CHAPTER SIX: METHODS 1

Inheritance and Interfaces

CSE 331 Software Design & Implementation

AP Computer Science Summer Work Mrs. Kaelin

GUI DYNAMICS Lecture July 26 CS2110 Summer 2011

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

5.6.1 The Special Variable this

CSCE 156 Computer Science II

Adapter Pattern Structural

CST242 Object-Oriented Programming Page 1

CSC 160 LAB 8-1 DIGITAL PICTURE FRAME. 1. Introduction

CSCI-142 Exam 1 Review September 25, 2016 Presented by the RIT Computer Science Community

Creating Java Programs with Greenfoot

To gain experience using GUI components and listeners.

CIT 590 Homework 10 Battleship

Chapter 10 Classes Continued. Fundamentals of Java

Decisions: Logic Java Programming 2 Lesson 7

Programming Languages and Techniques (CIS120)

5. In JAVA, is exception handling implicit or explicit or both. Explain with the help of example java programs. [16]

Lecture 19 GUI Events

Slide 1 CS 170 Java Programming 1 Testing Karel

COP 3330 Final Exam Review

Programming Languages and Techniques (CIS120)

Solution register itself

G51PGP Programming Paradigms. Lecture 008 Inner classes, anonymous classes, Swing worker thread

Final Exam CS 251, Intermediate Programming December 13, 2017

CS 3331 Advanced Object-Oriented Programming. Final Exam

CS/ENGRD 2110 SPRING 2018

Logistics. Final Exam on Friday at 3pm in CHEM 102

Inheritance and Interfaces

Software Paradigms (Lesson 3) Object-Oriented Paradigm (2)

Object Oriented Programming. Java-Lecture 11 Polymorphism

Java Programming Lecture 6

1. (5 points) In your own words, describe what an instance is.

Global Gomoku Lab 4 in D0010E

Programming Languages and Techniques (CIS120)

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

COURSE 2 DESIGN PATTERNS

Implementing Graphical User Interfaces

UCLA PIC 20A Java Programming

Abstract Classes and Interfaces

8. Polymorphism and Inheritance

+! Today. Lecture 3: ArrayList & Standard Java Graphics 1/26/14! n Reading. n Objectives. n Reminders. n Standard Java Graphics (on course webpage)

PART1: Choose the correct answer and write it on the answer sheet:

Check out FilesAndExceptions from SVN. Exam 2 Review File I/O, Exceptions Vector Graphics Project

M257 Past Paper Oct 2008 Attempted Solution

[ L5P1] Object-Oriented Programming: Advanced Concepts

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

Subclass Gist Example: Chess Super Keyword Shadowing Overriding Why? L10 - Polymorphism and Abstract Classes The Four Principles of Object Oriented

SE1021 Exam 2. When returning your exam, place your note-sheet on top. Page 1: This cover. Page 2 (Multiple choice): 10pts

CSCI 136 Written Exam #1 Fundamentals of Computer Science II Spring 2015

Practice for Chapter 11

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

CO Java SE 8: Fundamentals

CS111: PROGRAMMING LANGUAGE II

CS 3331 Advanced Object-Oriented Programming Final Exam

CS211 GUI Dynamics. Announcements. Motivation/Overview. Example Revisted

Inheritance, Polymorphism, and Interfaces

Slide 1 CS 170 Java Programming 1 Arrays and Loops Duration: 00:01:27 Advance mode: Auto

CMSC 132: Object-Oriented Programming II

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

Abstract Classes and Polymorphism CSC 123 Fall 2018 Howard Rosenthal

Critical Thinking Assignment #6: Java Program #6 of 6 (70 Points)

Review Chapter 6 in Bravaco. Short Answers 1. This type of method does not return a value. a. null b. void c. empty d. anonymous

Transcription:

CS 170 Java Programming 1 Week 15: Interfaces and Exceptions

Your "IC" or "Lab" Document Use Word or OpenOffice to create a new document Save the file as IC15.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 15" Start DrJava and we'll review a few basic inheritance concepts from last week

Week 14 Review Two basic strategies for building new classes Specialization (regular) inheritance Subclass inherits non-private attributes and methods of superclass (but not constructors), adds members Example of an isa relationship; subclass object is substitutable for instance of superclass Composition: create new type with instances as parts Example of a hasa relationship Forward or delegate requests to instance variables

Introducing Abstract Classes Classes using the modifier abstract in the header public abstract class Shape { private int x, y; } The Shape class contains fields (x andy) that can be used to store its location on the display Add other fields and methods just like a regular class

Why Abstract Classes? Abstract classes allow you to create generic classes Common functionality only needs to be written once Know a method is needed but don t know the details A program like Visio needs to draw() shapes Each different kind of shape is drawn in a different way A generic deal() method for CardGame is useless Each concrete game deals its cards differently Abstract classes guarantee that all subclasses will implement a particular method, like draw() or deal()

Abstract Class Vocabulary Abstract classes are "incomplete" They cannot be used to create objects They may be extended to create new classes Abstract classes represent "generic" functionality The Component class is abstract, for instance It contains methods common to Buttons and Labels You cannot create a Component object You can create a Component variable You can also extend the Component class The subclasses are called concrete classes

Give Yourself a Hand 15.1: open the Hand class in DrJava Represents a generic hand of cards Add code to make Hand an abstract class Shoot a screen-shot 15.2: modify BeginnersBlackjack Add two Hand instance variables Name one player and the other dealer What happens if you initialize the variable? Try it and shoot a screen-shot

Abstract Methods An abstract method is a mandatory method Use the modifier abstract when defining the method Replace the body of the method with a semicolon public abstract class Shape { private int x, y; public abstract void draw(graphics g); } Class may also have normal methods

Evaluate Your Hand 15.3: add an abstract method to Hand Name the method evaluatehand() Returns an int representing the value of the specific hand based on the game being played (Snap) 15.4: add a regular method that calls your abstract method in the Hand class Name the method compareto(hand other) Return the difference between evaluating the current hand and the other hand. Snap a pic.

Extending an Abstract Class To use the abstract class, you extend the class and then override any (and all) abstract methods The resulting class is your concrete class 15.5: create a new class in DrJava Name: BlackjackHand Specify the Hand class as the superclass Try to compile. DrJava tells you what method is missing. Add actual scoring code from evaluatehand.txt (Q:) Uncomment testing code in init(), run and snap

Show the Score 15.6: write a showscore() method that takes a Hand object as its parameter Inside the method call the evaluatehand() method and display the result in the statuslbl on the screen. Call showscore() with your player variable Run and shoot a screenshot NOTICE: this is Polymorphism

What Are Interfaces? Something like an extremely abstract class Groups together otherwise unrelated classes An abstract class works with related classes An interface specifies what methods must be written Interfaces guarantee that an object will know how to respond to a particular message If you implement Comparable, Java "knows" your class contains a compareto() method An interface can contain onlyabstract methods Can write generic methods that accept interface types

Defining Interfaces Place in a file with the extension.java, just like a class Use the keyword interface instead of class public interface Paintable { public void paint(graphics g); } All methods are automaticallyabstract You don't have to use the abstract keyword The interface and all methods must be public

Using Interfaces You don't extend an interface, you implement it public class Whatever extends Widget implements Paintable { // Implement interface methods here } Class must contain a paint() method You may implement multiple interfaces

Sorting Cards In the Deck class, we used shuffle() to shuffle the Cards inside an ArrayList The shuffle() method orders the elements randomly The contents of each element don't matter The Collections class also has a sort() method Put each of the elements in a specific order 15.7A: Add a sort() method to the Deck class Call the Collections.sort() just like shuffle Compile: shoot a screenshot of error

The Problem with Sorting The sort() method doesn't care what kind of thing we want to sort, but it doesn't know how to sort cards! The PlayingCard class itself has to tell it which card must go first and when two cards are equal Do this by implementing the Comparable interface 15.7B : add this to the PlayingCard class header: implementscomparable<playingcard> Compile. Notice DrJava tells you what method to add You must add a compareto() method Snap a picture of the error

The Comparable Interface To make sort() work, we a method with this signature: // a.compareto(b) returns 0, >0, or <0 public int compareto(card othercard) { } If two cards are equal, return 0 If a is < b then return < 0; If a is > b then return > 0 Uncomment compareto() at bottom of class Places cards in rank-major order 15.7C: run CardSortDemo, press each button and snap

Java's Event-handling Java uses interfaces for all of its event handling These interfaces are called "listeners" Defined in the java.awt.event package Implement interfaces to respond to these events The classes you create to do this are called listener classes Most common "real-world" method of event handling uses anonymous inner classes to respond to each event The inner class will implement the appropriate interface This listener class will be defined inside your class

Subscribing to Events A JButton needs to know that you want events This works like subscribing to the paper You may be able to read it, but unless you "sign up" it won't be delivered to your door Add code like this to hook up the button: ActionListener handler = new MyHandler(); thebtn.addactionlistener(handler); Creates an instance of the MyHandler class and tells the thebtn to notify it whenever it is clicked

Anonymous Inner Classes Since we need only one handler class for each button, we can create an object at the same time as we define our class. Neither the class nor the object are named. This simplified syntax works for both classes and interfaces btn.addactionlistener( new ActionListener() { // anonymous class public void actionperformed(actionevent e) { // Carry out your actions here } } ); Called when clicked Access to outer vars

Deal a Hand 15.9: Locate the code for actionperformed() attached to the dealhandbtn Move the code from the "testing" section inside it Add dealerpile.removeall() as first line Removes cards from previous hands Modify the code so that the newdeck() method is called only if deck is null or it has fewer than 2 cards Run and click the dealhandbtnjbutton Shoot me a screen-shot

JButton Event Enabling Often, you'll want to enable or disable buttons depending on the results of a particular action Do that with the JButton'ssetEnabled() method newhandbtn.setenabled(true); // active hitbtn.setenabled(false); // deactivate 15.10: modify showscore() method Score 21: Win message, hit and stand off, deal on Score < 21: Hit or stand activated, deal off Score > 21: Bust message, hit & stand off

Do you want to Hit? 15.11: Here's what you should do for the Hit button If the deck has less than 1 card, call newdeck Add the top card to the player's hand Run and make sure you can hit. Snap a picture

Standing and Scoring 15.12: Here's what you should do for the Stand button Call newdeck if there are fewer than 2 cards Create a new hand for the dealer and add two cards Use a loop to keep adding cards to the dealer's hand while the score is <= 17. Call newdeck if you run out of cards Display the dealers cards in the dealerpile Call scoregame(), passing dealer and player. Run, play a game and snap me a picture.

Finishing Up If you didn't complete your IC "lab" document you may follow along in the online lessons this week to get the parts that you missed. Otherwise, just submit it now. Homework Assignments Six homework problems, no quiz 5 ArrayList problems 1 Inheritance problem Final Exam and Proficiency Makeup Next Week Sample exam available on BBV