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