6.005 3. Subclassing and interfaces

Add to Favourites
Post to:

MIT OpenCourseWare http://ocw.mit.edu 6.005 Elements of Software Construction Fall 2008 For information about citing these materials or our Terms of Use, visit: http://ocw.mit.edu/terms. Subclassing and Interfaces Rob Miller Fall 2008 © Robert Miller 2008 Getting Weather Information Let’s build on Page to get weather conditions ¾Yahoo Weather feed:http://weather.yahooapis.com/forecastrss?p=02139 ¾Returns an XML page that looks like this: ...<...Conditions pmtitle>for Cambridge, MA at 3:54 pmEDT......Some string manipulation can extract the current weather condition: Page p = new Page(new URL("http://weather...=02139");String yweather = Match.between(p.getContent(), ""); String condition = Match.between(yweather, "text=\"", "\""); © Robert Miller 2007 Today’s Topics More Java ¾subclassing¾interfaces ¾packagespackages¾collections© Robert Miller 2007 Simple Pattern Matching public class Match { /* Finds the first match to pattern in string, and* returns the rest of the string. e.g., * after("Your Name: Ben", "Name: ") => "Ben“ * Returns *//null if pattern never occurs in string. public static String after(String string, String pattern) /* Finds the first match to pattern in string, and * returns the part of the string before it. e.g.,* before("hello/there", "/") => "hello“ * Returns null if pattern never occurs in string. */public static String before(String content, String pattern) /* Finds the first match to left in string, and * the first match to right after that, and* returns the substring between the two matches. * e.g. between("a bold word", "", "") => "bold“ * Returns null if left...right never occurs in string.*/public static String between(String content, String left, String right) © Robert Miller 20071 Weather as a Subclass of Page public class Weather extends Page {extends means Weather is a subclass of Page private String condition;private int temperature;public Weather(String zipcode) throws IOException { super("http://weather.yahooapis.com/forecastrss?p=“+ zipcode);}super () calls the superclass’s constructor public String getCondition() {return condition;}public int getTemperature() { return temperature;}...As a subclass of Page, Weather g, inherits the methods and fields of Page: url, content, getURL(), getContent(), download() } © Robert Miller 2007 Declared Type vs. Actual Type ¾A variable has a declared type at compile-time ¾The variable refers to an object with an actual type at runtime Actual type is either the same or a subclass of declared type static (compile time) dynamic (run time) Page p = new Page(“http://...”); p Æ Page object p.getContent(); p = new Weather(“02139”); p Æ Weather object p.getContent(); p.getTemperature(); Weather has the same methods and fields that Page does (it inherits them) so it’s © Robert Miller 2007 them), it s safe for p to refer to a Weather object at runtime But Java’s static type checking won’t allow you to use a method or field that isn’t in the declared type of the variable (Page), even if it’s in the actual type at runtime (Weather). Class Hierarchy and java.lang.Object Subclassing creates a hierarchy ¾Every class implicitly extends java.lang.Object, the root of the hierarchy ¾So every class inherits methods from Object, e.g. equals() and toString() java.lang.Object Page java.lang.String java.net.URL Weather © Robert Miller 2007 More Access Control ¾protected fields and methods can be used in this class or any of its subclassesprotected URL url;protected String content;• This would allow Weather to access the fields it inherits from Page • But it can already access them through getURL() and getContent(), so we won’t bother¾But let’s move Page’s downloading code into a protected method:protected void download() throws IOException { Page p = getPageFromCache(url); if (p != null) {(){ this.content = p.content; } else { this.content = Web.fetch(url); putPageInCache(this); } } © Robert Miller 2007 2 extends means Weather is a  subclass of Page super () calls the superclass’sconstructor As a subclass of Page  Weather  inherits the methods and fields  of Page: url, content, getURL(),  getContent(), download() java.lang.Object Page java.lang.String Weather java.net.URL= © Robert Miller 2007 Overriding a Method Method Selection public class Overriding provides a new body for an inherited method Weather extends Page { The actual type of the object is used to select the ... method body to call @Override protected void download() throws IOException { static (compile time) dynamic (run time) super.download(); super.method (...) calls the superclass’s implementation of method String yweather = Match.between(this.getContent(), ""); this.condition = Match.between(content, "text=\"", "\""); this temperature = Integer valueOf(Match between(content, this.Integer.Match."temp=\"", "\"")); } }Don’t confuse overloading (two methods in the same class with the same name but different arguments) and overriding (a method implemented in both superclass and subclass, with the same name and same arguments) © Robert Miller 2007 Weather Data from the Cache Page p = new Weather(“02139”); p Æ Weather object p.download(); calls Weather’s download() method, not Page’s The declared type of the variable is irrelevant to method selection declared type is used by static type checking, to ensure that the method will exist at runtime but actual type is used at runtime to select the method body to call The location of the method call is also irrelevant to method selectionPage’s constructor has a call to download() in it. Which version of download() will it call?© Robert Miller 2007 Type Testing and Downcasting What’s in Page’s cache now? ¾Even though the cache’s declared type is Page[], at runtime it might contain a mix of Page and Weather objects ¾This is OK, because all those objects behave like Pages ¾But what if we want to take advantage of the cached Weather objects – i.e., reuse their temperature and condition values? ¾First we have to make the cache accessible to Weather: protected static Page getPageFromCache(URL url) { ... } protected static void putPageInCache(Page page) { ... } ¾Then we try this code in Weather.download(): Page cachedPage getPageFromCache(this url);this.if (cachedPage != null) {this.temperature = cachedPage.temperature;Type error ‐‐the declared type, Page, doesn’t have this field. ... © Robert Miller 2007 a instanceof B tests whether a’s actual type is B (or a subclass of B) Page cachedPage = getPageFromCache(this.url);if (cachedPage instanceof Weather) {//f d h ihhfound a weather page in the cache Weather cachedWeather = (Weather) cachedPage; this.condition = cachedWeather.condition; this.temperature = cachedWeather.temperature; } else { //extract condition and temperature from the content ... }} Fix the type error by downcasting from Page to Weather, which asserts to Java that you knoww (because you just tested it with instanceof) Don’t confuse casting of object types (which merely changes the declared type at compile time and doesn’t affect the runtime object at all) and coercion of primitive types (which actually produces a different runtime value; e.g. (int)0.5 produces the value 0). They use the same syntax in Java! 3 Don’t confuse overloading (two methods in the same class with the same  name but different arguments) and overriding (a method implemented in  both superclassand subclass, with the same name and same arguments)  Type error  ‐‐the declared type, Page, doesn’t  have this field. Fix the type error by downcasting from Page to Weather, which  asserts to Java that you kno it will be a Weather object at runtime  (because you just tested it with instanceof) Don’t confuse casting of object types (which merely changes the declared type at  compile time and doesn’t affect the runtime object at all) and coercion of  primitive types(which actually produces a different runtime value;  e.g. (int)0.5 produces the value 0).  They use the same syntax in Java!  wB tR ti E ti Exception Class HierarchyMalformedURLException FileNotFoundException NullPointerException ArrayOutOfBoundsException Exceptions are normally checked at compile time –Java requires them to be either caught or declared. But RuntimeExceptons are unchecked at compile time. You can catch or declare them, but Java doesn’t require it. © Robert Miller 2007 Exception RuntimeException Page Cache as a Class Recall how we cached web pages using static fields and methods in Page private static Page[] cache; private static int cachePointer; protected static Page getPageFromCache(URL url) { ... }protected static void putPageInCache(Page page) { ... }It’s sensible to wrap this behavior up into its own class ¾Easier to understand: a “cache” abstraction with get and put operations cache ¾Ready for change: we can easily change the data structure we use toimplement it, even if we reuse the cache idea throughout the program¾Safe from bugs: users of the cache don’t have access to its internalrepresentation, only to the get and put operations© Robert Miller 2007 Multiple Catch Clauses try { fetch("http://www.mit.edu/"); } catch (MalformedURLException e) {System.out.println("Bad URL: " + e);} catch (IOException e) { System.out.println("IO problem: " + e); } a thrown exception is tested against each clause until finding the first one whose declared type is compatible with the exception object’s actual type What clause does “htt://www.mit.edu” run?What clause does “http://www.mit.edu/foobar” run?What if we switch the order of the clauses? (Tricky! What’s the relationship between the MalformedURLException and IOException classes? )© Robert Miller 2007 Cache Implemented with an Array public class ArrayCache {private Page[] array = new Page[100];private int pointer = 0;representation public Page get(URL url) { for (Page page : array) { operations&& page.getURL().equals(url)) {if (page != null return page;}}return null; }public void put(Page page) { array[pointer] = page; ++pointer; if (pointer >= array.length) pointer = 0; }} © Robert Miller 2007 This class needs no constructor, because all its fields are initialized in their declarations. 4 Exception MalformedURLException NullPointerException FileNotFoundException ArrayOutOfBoundsException Exceptions are normally checked at  compile time – Java requires them to be  either caught or declared. onsare  unchecked at compile time.   You can catch or declare  them, but Java doesn’t  require it. But RuntimeExcepti But  RuntimeExcepti a thrown exception is tested against each clause until  finding the first one whose declared type is  compatible with the exception object’s actual type representation operations This class needs no constructor, because all its  fields are initialized in their declarations. IOException RuntimeException Cache Interface The essence of the cache are its get/put operations ¾This essence can be captured by a Java interface, which contains only method declarations (not method bodies) public interface Cache {public Page get(URL url);public void put(Page page);} interfaces can’t have constructors or fields either – nothing but method declarations ¾ A class implements the Cache interface by declaring it and providing bodies for the two methods public class ArrayCache implements Cache {...ppublic Pagge get((URL url) { ... }}g ){public void put(Page page) { ... }}¾A caller can use Cache as an object type Cache cache = new ArrayCache(); cache.get(new URL(“http://www.mit.edu”)); © Robert Miller 2007 since an interface has no constructor, you can’t say new Cache() –you need to construct an object of a class that implements the interface Namespaces Packages create separate namespaces for class names ¾So you can use short names like Page and Cache without worrying that those classes already exist in another packageNamespaces are a vital pattern for organizing systems ¾Easier to understand: names can be simpler and shorter ¾Ready for change: reduces the scope of possible conflicts for new names ¾Safe from bugs: names added in other namespaces don’t affect this one Widely used in Java and other systems ¾Class creates a namespace for methods and fields¾{ } scope) for local variablesStatement block {...} creates a namespace (¾Domain name (@mit.edu) creates a namespace for user namesNamespaces are often hierarchical ¾Sometimes inherit: e.g. local variables are inherited from enclosing scopes ¾Sometimes don’t: subpackages do not inherit classes from their parent package (and import web.* doesn’t include web.cache.*)© Robert Miller 2007 Defining a Package Hierarchy Let’s organize our classes into packages ¾web package: Page,Weather¾web.cache package: Cache,ArrayCachePackages are folders in the filesystem ¾The web.cache package corresponds to the path web/cache ¾The folder contains a set of classes and interfaces, each in its own file,which all start with “package web.cache;” as their first line¾Eclipse handles this automatically when you make new packages and drag & drop classes into them © Robert Miller 2007 Cache Implemented With a List public class ListCache implements Cache {private List list = new ArrayList();public Page get(URL url) {for (Page list){page : list) {if (page.getURL().equals(url)) {return page; } }return null;} public void put(Page page) { list.add(page);}}The List interface contains operations for a sequence data type: add(), get(), size(), etc. . List and ArrayList are generic types, which means they take a type parameter. List represents a list of Type objects. Here we use List for a list of Page objects. © Robert Miller 2007 5 since an interface has no  constructor, you can’t say  new Cache() – you need to  construct an object of a  class that implements the  interface List and ArrayListare generic types, which means they take a  type parameter.  List represents a list of Type objects.   Here we use List for a list of Page objects.             . The ArrayListclass implements List  using an array that grows as needed using an array that grows as needed.© Robert Miller 2007 Hailstone Sequences Done Right For variable-length sequences, Lists are much better than Strings or arrays/* Returns the hailstone sequence from n to 1 as a list. * e.g. if n=5, then returns the list (5,16,8,4,2,1). * Requires n >= 1. */public static List hailstoneSequence(int n) {List list = new ArrayList();list.add(n);while (n != 1) {if (isEven(n)) n = n /2; else n = 3 * n + 1; list.add(()n);}return list;} Notice we used List rather than List. Generic types can only take object types as parameters, not primitive types. But every primitive type has a related object type (int/Integer, char/Character, long/Long, etc.), and Java automatically converts between them. Anonymous Classes An interface can be implemented by a nameless class Starts like a constructor call... Cache cache = new Cache() {private Page onlyPage; public Page get(URL url) {if (onlyPage != null && onlyPage.url.equals(url)) { return onlyPage;} else {return null; }} public void put(Page ...but includes a class body defining the interface’s methods (plus other fields and methods if needed) page) { onlyPage = page;}};An anonymous class definition effectively creates a new class, but doesn’t give it a name. Anonymous classes are frequently used in user interface programming, which is full of little interfaces to implement. Cache Implemented With a Map public class MapCache implements Cache { private Map map = new HashMap();; public Page get(URL url) {return map.get(url);}public void put(Page page) {map.put(page.getURL(), page);}}The Map interface represents a set of ( key, value) pairs and y, ) p makes it easy to look up the value associated with a key. Here, the key is a URL, and the value is the page for that URL. The HashMap class implements Map using a hash table (we’ll have more to say about this in a later lecture). Map is a powerful interface. It’s ideal for a cache, but it has many other uses too. Learn it well and use it carefully! © Robert Miller 2007 Enumerations enum defines a type with a small finite set of values ¾Contrast with Page, which has an unbounded set of values (web pages!) ¾Enums can have methods and fields too, like classes public enum CompassPoint { NORTH,SOUTH,EAST,WEST;enum values are referenced like public static constants –e.g. CompassPoint.NORTH } bli { public enum ANSWER YES,NO,CANCEL;} © Robert Miller 2007 © Robert Miller 2007 6 Notice we used List rather than List.  Generic types can  only take object types as parameters, not primitive types.  But every  primitive type has a related object type (int/Integer, char/Character,  long/Long, etc.), and Java automatically converts between them. makes it easy to look up the  value associated  with a key. Here, the key is a URL, and the  value is the page for that URL. The Map interface represents  a set of  The HashMap class implements  Map using a hash table (we’ll  have more to say about this in a  later lecture). Map is a powerful interface.  It’s ideal for a cache, but it has  many other uses too.  Learn it well and use it carefully! enum values are referenced like  public static constants – e.g.  CompassPoint.NORTH Starts like a constructor call... (key, value  pairs and c stat c t ass o t Switch Statement switch tests a value against a set of cases ¾equivalent to a sequence of if-else clauses¾the value can be either an enum or integer type (int, char, etc.)public static int degrees(CompassPoint point) { pub deg ees(Co p po t) int result; switch (point) { case NORTH: result = 0; break; case EAST: result = 90; break; case SOUTH: result = 180; break; case WEST: result = 270; break; default: throw new RuntimeException("invalid compass The cases of a switch must be terminated by break, or they will fall through to the next case! point");point ); } return result; } default is like the else clause of a switch –it’s good practice to always include one. Often it just throws an exception. © Robert Miller 2007 Summary Subclassing ¾Inheritance of fields and methods¾Declared type vs. actual type¾Overriding and method selectionOverriding selection¾DowncastingInterfaces ¾An interface captures the essence of a class: its method specifications Packages ¾Packages define separate namespaces for classes¾NNamespaces are a usefull organiiziing principlle forllarge systemsf iif t Collections ¾List is a list of Type objects¾Map is a set of pairs¾Generic types like List and Map take a type parameter © Robert Miller 2007 7 The cases of a switch must be  terminated by break, or they  will fall through to the next  case! default is like the else clause of a switch – it’s good practice  to always include one. Often it just throws an exception.

Description
In this lesson , you learn about 1. Subclassing:Inheritance of fields and methods,Declared type vs. actual type,Overriding and method, selection, Overriding selection, Downcasting 2.Interfaces: An interface captures the essence of a class: its method specifications 3.Packages:Packages define separate namespaces for classes 4.Namespaces are a usefull organiiziing principlle forl large systems and 5.Collections: List is a list of Type objects,Map is a set of pairs,Generic types like List and Map take a type parameter .

Instructors: Prof. Daniel Jackson, Prof. Robert Miller MIT Course Number: 6.005 Level: Undergraduate, 6.005 3. Subclassing and interfaces, Elements of Software Construction, Electrical Engineering and Computer Science, Engineering, Massachusetts Institute of Technology: MIT Open Course Ware, http://ocw.mit.edu (01-11-2011).License: Creative Commons BY-NC-SA: http://ocw.mit.edu/terms/#cc".

Comments

Want to learn?

Sign up and browse through relevant courses.

Name:
Your Email:
Password:
Country:
Contact no:


Area code Number
Subjects you are interested in:
Word verification: (Enter the text as in image)


Sign Up Already a member? Sign In
I agree to WizIQ's User Agreement & Privacy Policy
LearnOnline Through OCW
OpenCourseWare
User
102 Followers

Your Facebook Friends on WizIQ

Explore Similar Courses

Develop Android Apps with Java

Price:$300
$40

SAVE 86%

Give live classes, create & sell online courses

Try it free Plans & Pricing

Connect