420 likes | 608 Views
Midterm 2 Review Decorator. COMP 401, Spring 2013 Lecture 17 3 /19/2013. How Now Brown Cow (Professor?). Revised assignment schedule: A5: Wed. 3/27 A6: Fri. 4/5 A7: Wed. 4/17 A8: Fri. 4/26 Midterm 2 still this Friday Today Midterm 2 Review, start of Decorator Thursday
E N D
Midterm 2 ReviewDecorator COMP 401, Spring 2013 Lecture 17 3/19/2013
How Now Brown Cow (Professor?) • Revised assignment schedule: • A5: Wed. 3/27 • A6: Fri. 4/5 • A7: Wed. 4/17 • A8: Fri.4/26 • Midterm 2 still this Friday • Today • Midterm 2 Review, start of Decorator • Thursday • Decorator finished, start of Observer/Observable
Inheritance • Subinterfacing • Extending an existing interface • Subclassing • Extending an existing class
Extending Interfaces • Adds methods to contract. • Original: • parent interface, super interface • New: • subinterface, child interface, extended interface • Created by using the “extends” keyword. public interface CompressedMedia extends Media { intgetCompressedSize(); intgetUncompressedSize(); Media uncompress(); }
Extension Creates Hierarchy Media • Is-A relationship is transitive up the hierarchy. extends Compressed Media Methods for both must be provided. public class Song implements CompressedMedia { ... Song s = new Song(); CompressedMedia cm = (CompressedMedia) s; Media m = (Media) s; Song s2 = (Song) m; OK because s “is a” Compressed Media OK because s is a Media by virtue of extension. Casting from interface back to specific object type is allowed, but at runtime, if the object’s type does not actually match, a runtime exception will be thrown.
Interface Extension vs. Interface Composition public interface Compressed { intgetCompressedSize(); intgetUncompressedSize(); Media uncompress(); } public interface Media { intgetLengthInSeconds(); double getLengthInMinutes(); intgetRating(); void setRating(intnew_rating); String getName(); } Instead of extending Media, Compressed is a separate interface and Song implements both. public class Song implements Compressed, Media { ... Song s = new Song(); Media m = (Media) s; Compressed c = (Compressed) s; Song “is a” Media AND Song “is a” Compressed.
Subinterface vs. Subclass • Extending interface only added behavior to contract. • Since interfaces don’t specify (and don’t care) how contract is fulfilled. • Extending class creates a new class that shares internal implementation details of its super class. COMP 401 :: Spring 2012
Is-A For Subclasses Objects of type A, implement interface InterA. A “is a” Inter A class A implements InterA { ... } class B extends A implements InterB { ... } class C extends B implements InterC { ... } Objects of type B, implement interface InterB and InterA. B “is a” A B “is a” InterA B “is a” InterB Objects of type C, implement interface InterC, InterB, and InterA. C “is a” A C “is a” B C “is a” InterA C “is a” InterB C “is a” InterC COMP 401 :: Spring 2012
Instance Fields • Subclass has direct access to public and protected instance fields. • Public: Everyone has access • Generally not a good idea. • Breaks encapsulation. • Private: Only class has access • Generally recommended as default. • Subclasses, however, also shut out. • Protected: Class and subclasses have access. • Like private (i.e., appropriate use of encapsulation) but allows for subclassing(even if outside of package) • lec9.v4 COMP 401 :: Spring 2012
Subclass Method Polymorphism • Subclass can overload methods in superclass. • Remember, overloading is providing a different version of an existing method. • An example of polymorphism • Method signature is different in some way. • lec10.v1
Overriding Methods • A subclass can “override” a super class method by providing its own definition. • Method signature must be the same. • Original method is visible from subclass • i.e., public, protected, or package-level access • lec10.v2
Class Polymorphism • Previously introduced the idea of “is-a” relationships • Between a class and interfaces implemented. • Between a class and its superclass hierarchy. • This is also an example of polymorphism • Covariance • Treating an instance of a subclass as a reference typed as the parent class. • This can be typed checked at compile type. • Contravariance • Treating a reference typed as the parent class as an instance of a subclass. • Contravariance can not be type checked in advance at compile time. • Fails if the object is actually “invariant” with respect to the subclass. • lec10.v4, lec10.v4main • Also demonstrates protected base class constructor
A Covariant Conundrum • Problem: • What should happen when an overriden method is called on a covariant reference? class A { public int m() {return 0;} } class B extends A { public int m() {return 1;} } class C extends B { public int m() {return 2;} } C c_obj = new C(); B b_obj = (B) c_obj; A a_obj = (A) c_obj; System.out.println(c_obj.m()); System.out.println(b_obj.m()); System.out.println(a_obj.m()); What should these lines print?
Virtual Methods • Different OOP languages choose to solve this problem in different ways. • C++, C# • Default is non-virtual solution. • Programmer can force virtual solution by marking a method with a special “virtual” keyword • Java • Methods are always virtual. • No special keyword needed. • lec10.v5
Abstract Classes and Methods • Parent class has no meaningful implementation of a method. • But part of interface of parent class • Expect subclass to provide it. • In these situations, we never expect (or want) the parent class to be instantiated directly. • We always make new objects using a subclass. • Syntax • Use “abstract” modifier when declaring parent class • Declare any methods that must be provided by subclass in parent • Add “abstract” modifier to method signature. • Follow signature with semicolon instead of method definition
Composition and Aggregation • Two design techniques for creating an object that encapsulates other objects. • Any specific situation is not necessarily strictly one or the other. • In a nutshull… • Composition • The individual parts that make up the whole are “owned” solely by the whole. • They don’t otherwise have a reason for being. • Aggregation • The individual parts that make up the whole may also exist on their own outside of the whole. • Or even as a component or part of other objects.
Characteristics of Aggregation • Encapsulated objects provided externally • As parameters to constructor • Getters and setters for these components often provided. • Encapsulated objects may be independently referenced outside of the aggregating object • Including possibly as part of another aggregation.
Characteristics of Composition • Encapsulated objects created internally • Usually within the constructor • No setters and often no getters • Encapsulated objects do not make sense outside of the abstraction. • Not shared with other abstractions • Functionality / state of encapsulated objects only accessible through the abstraction
Delegation • Claiming an “is-a” relationship with an interface but relying on another object to actually do the work. • Can occur with either aggregation or composition. • Although more common with composition • Composition example revisited • lec13.v3 • Both Car implementations also now claim Horn and/or AdjustableHorn interfaces as well. • Actual work of these interfaces delegated to internal horn.
Factory Design Pattern • When direct construction of an object is harmful • … or at least undesired • By “direct construction”, I mean by using the new keyword • Several different contexts when factory design pattern is appropriate: • Singleton • When there should only be one instance of a particular class in the whole system. • Multiton • When there should only be one instance of of an object associated with some identifying property • Dynamic subclass binding • When the specific subclass of an object can only be determined at the time that it is created • Complex construction • When the construction of the object requires complex validation and/or side effects that must be handled • When null should be a valid result
Factory Design Pattern • When direct construction of an object is harmful • … or at least undesired • By “direct construction”, I mean by using the new keyword • Several different contexts when factory design pattern is appropriate: • Singleton • When there should only be one instance of a particular class in the whole system. • Multiton • When there should only be one instance of of an object associated with some identifying property • Dynamic subclass binding • When the specific subclass of an object can only be determined at the time that it is created • Complex construction • When the construction of the object requires complex validation and/or side effects that must be handled • When null should be a valid result
SingletonOne Object To Rule Them All • When there should only be one instance of a particular class in the whole system at any given time. • Generally the object represents some sort of system-wide resource that may be needed by many objects in different parts of the software. • Modifies basic factory pattern by maintaining a single instance. • Created on demand when first requested • Lazy initiation • Stored in a private static variable and retrieved by a static getter • Static getter is the factory method • lec16.v1 • Simple logging mechanism. • lec16.v2 • A singleton variant that employs delegation.
Multiton • Maintains a single instance of the object with regard to a uniquely identifying characteristic of object. • Multiton factory method • Static (as per the general factory pattern) • Provided all info. needed to create a new object if necessary. • Determines if corresponding object already exists. • If so, returns the existing object • If not, creates the new object and inserts it into a static structure • Usually implemented using a “map”
Dynamic Subclass Binding • Useful when choice needs to be made between several different subclasses • Delegates decision about which to use to factory • Factory method given any/all information that is relevant to decision and for creating new object if necessary. • lec16.v5
Exception Handling in Java • Three kinds of exception: • Checked exceptions • Generally valid situations that application should be able to anticipate and deal with. • Error • External conditions that application generally can’t anticipate or do anything about. • Runtime exceptions • Internal conditions that usually indicate an error in logic COMP 401 :: Spring 2012
Specifying Checked Exceptions • Checked exceptions must be specified as part of method signature. • Checked exceptions are any exceptions that are a subclass of Exception but not Error or RuntimeException. • Must indicate specific type of exception object that will be thrown. • After parameter list, before method body. • Keyword “throws” followed by comma separated list of possible exception object types. • Example: public Sushi getSushiAt(int pos) throws BeltPositionEmptyException { ... } COMP 401 :: Spring 2012
Catch or Specify Requirement • Any method that calls another method that could throw a checked exception must either: • “catch” the exception, or... • “specify” the exception • Declare that this method could result in the exception. • Even thought this method didn’t throw it. • Compile-time requirement for Java • Won’t even run. COMP 401 :: Spring 2012
Catching Exceptions • try – catch – finally try { // Code here cause an exception. } catch (ExceptionTypeA name) { // Code here executes if ExceptionTypeA is raised // Variable “name” is set to exception object. } catch (ExceptionTypeB name) { // Code here executes if ExceptionTypeB is raised // Variable “name” is set to exception object. } finally { // Code here always gets executed. } COMP 401 :: Spring 2012
Catching Exceptions • try – catch – finally try { // Code here cause an exception. } catch (ExceptionTypeA name) { // Code here executes if ExceptionTypeA is raised // Variable “name” is set to exception object. } catch (ExceptionTypeB name) { // Code here executes if ExceptionTypeB is raised // Variable “name” is set to exception object. } finally { // Code here always gets executed. } COMP 401 :: Spring 2012
General Principle: Be Specific • Use an existing exception type. • There are lots. • If semantics of the exception match well, then go ahead and use it. • Create your own exception type. • Subclass either RuntimeException or Exception • lec17.v1 • Notice how exception raised by Scanner transformed into context-specific exception for Playlist. • Also note how error message can be retrieved from exception object. • See handling of PlaylistFormatException in main() • See reference page for Exception for more. COMP 401 :: Spring 2012
General Principle: Catch Late • Exceptions should rise to level where application has enough context to deal with them effectively. • Catching exception just because you can not always the right thing to do. • Look again at lec17.v1 • In particular, note handling of FileNotFoundException • lec17.v2 • Note printStackTrace() method of Exception in Main1 • Note differences in how FileNotFoundException handled in Main1 vs. Main2 COMP 401 :: Spring 2012
General Principle: Throw Early • Validate values as early as possible. • Rather than waiting for exception generated by invalid values sent to other code. • Particularly apropos for null values that cause NullPointerException • Exception generated is not very specific • Almost always have to look higher in the stack trace to see what the real problem is. • lec17.v3 • Tests for one type of illegal filename (i.e., empty string) before actually trying to open file. COMP 401 :: Spring 2012
SongLog • Goal: • Create an object to represent a song “log” (i.e., record of what songs were played) • Provide ability to answer queries about songs played. • Design: • void recordInLog(SongInterfaces) • void recordInLog(SongInterfaces, Date time) • Date lastPlayed(SongInterfaces) COMP 401 :: Spring 2012
Date • Java’s class for dealing with Date • Represents a point in time down to millisecond precision. • Separate classes for formatting and calendar operations. • Calendar • DateFormat • Provides a number of pre-defined formats • SimpleDateFormat • Allows you to construct customized formats • See Date tutorial on Oracle site for more. COMP 401 :: Spring 2012
SongLog version 1 • lec12.v3 • Strategy: • Maintain two array lists • One for songs • One for dates COMP 401 :: Spring 2012
SongLog v1 critique • It works, but not as clean as it could be. • Why? COMP 401 :: Spring 2012
Decorator Pattern • Useful when you want to add additional state or functionality to a class without formally subclassing. • When might that be? • Additional state/functionality is auxiliary to object’s main purpose. • Additional state/functionality is local to a collection or some other class encapsulating the object. • SongLog for example. • As a workaround for multiple inheritance • Want to build up an object with subsets of different functionality. • Decorator pattern is a form of delegation. COMP 401 :: Spring 2012
Decorator Pattern Recipe • Setting up: • Start with original interface. • If decorating a class without an interface, refactor original class to have an interface. • In our example: • Song (this is the interface) • SongImpl COMP 401 :: Spring 2012
Decorator Pattern Recipe • Step 1: • Extend interface, declaring additional functionality. • In our example: • LoggedSong • Date getDate(); COMP 401 :: Spring 2012
Decorate Pattern Recipe • Step 2: • Create class that implements decorated interface. • Provide constructor that takes an object of the original (i.e., undecorated) interface type and possibly any additional state information needed for decorated behavior. • Delegate original interface methods to encapsulated object. • Provide implementations for decorated behavior. • In our example: • LoggedSongImpl • public LoggedSongImpl(SongInterface s, Date d) • Date getDate() COMP 401 :: Spring 2012
SongLog v2 • This version decorates the songs as logged songs and then stores them. COMP 401 :: Spring 2012