6.005 2. Classes ,Exceptions, Input/Output and more in Java

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. (name, retur which Classes Rob Miller Fall 2008 © Robert Miller 2008 Review: How To Write a Method/* * Returns the contents of the web page identified 1. Write the method signature n type, arguments */public static String fetch(String urlString) { * by urlString, must be a valid URL. * e.g. fetch("http://www.mit.edu") * returns the MIT home page as a string of HTML. ... } 2. Write a specification (a comment that defines what it returns, any side‐effects, and assumptions about the arguments. 3. Write the method body so that it conforms to your specification. (Revise the signature or specification if you discover you can’t implement it!) © Robert Miller 2007 Today’s Topics object-oriented programming in Java ¾exceptions¾classes¾subclassingsubclassing© Robert Miller 2007 Getting Data from the Web import java.net.URL; /* imports the class URL from the java.net package * Returns the contents of the web page identified * by urlString. e.g. fetch("http://www.mit.edu") * returns the MIT home page as a string of HTML.*/public static String fetch(String urlString) {URL url = new URL(urlString);...} constructs a new URL object © Robert Miller 2007 1 1. Write the method signature (name, return type, arguments 2. Write a specification (a comment  that defines what it returns, any sideeffeects and assumptions about the  arguments. 3. Write the method body so that it conforms to your  specification.  (Revise the signature or specification if  you discover you can’t implement it!) imports the class URL from  the java.net package constructs a new URL objectClasses in Other Packages Java classes are arranged in packages ¾java.lang.String¾java.lang.Math¾java net URLjava.net.URLImport statements at top of Java file bring in the classes you need ¾import java.net.URL;¾import java.net.*;¾java.lang.* package is imported automatically, so we don’t have to do this with Stringg or Math,, for exampple © Robert Miller 2007 Two Ways To Deal With Exceptions public static String fetch(String urlString) {try {URL url = new URL(urlString);...} catch (MalformedURLException e) { catch the exception and deal with it MalformedURLException System.out.println(“Badly formed URL: “ + urlString); e.printStackTrace(); //System.exit(0); }} Exiting the whole program is generally not useful. Catching the exception makes sense when there’s something fetch() can do to fix the problem. public static String fetch(String urlString) throws MalformedURLException { URL url = new URL(urlString);...} This is probably the right thing to do in this case, because it’s the caller’s fault for passing a nonsensical URL. fetch() can’t fix it. declare the exception in the method signature, so that it’s passed on to the caller of fetch() to deal with it © Robert Miller 2007 Exceptions Exceptions are abnormal return conditions from a method¾Instead of returning a value normally, the method throws an exception ¾Exceptions usually indicate conditions necessarilyExceptions error conditions, but not necessarily ¾Exceptions are objects. Usually just have a message, but can carry other data as well Throwing an exception¾throw statement throws an exception objectthrow new MalformedURLException(“bad URL:“ + urlString);¾throw is like return – the method immediatelyy stopps,, but instead ofreturning a value, it propagates the exception © Robert Miller 2007 Getting Data from the Web public static String fetch(String urlString) throws MalformedURLException, IOException { URL url = new URL(urlString); //open a stream from the web server InputStream input = url.openStream();InputStreamReader reader = new InputStreamReader(input);//create a stream that appends data together into a StringStringWriter writer = new StringWriter(); //copy from the web server stream to the string stream//(defined in a few slides) copyStream(reader, writer); //return the string we created return writer.toString();}© Robert Miller 2007 2 Exiting the whole program is generally not useful.  Catching the exception  makes sense when there’s something fetch() can do to fix the problem.  This is probably the right thing to do in this  case, because it’s the caller’s fault for passing a  nonsensical URL.  fetch() can’t fix it. declare the exception in the  method signature, so that  it’s passed on to the caller of  fetch() to deal with itBytes vs. Chars Byte is an 8-bit value ¾Older programming systems used 7-bit (ASCII) or 8-bit character sets,which could represent at most 256 different characters¾The multilingualWeb demands a lot more! ¾But network connections and files are still generally represented as asequence of 8-bit byte values¾java.io.InputStream and java.io.OutputStream are streams of bytesChar is a 16-bit value ¾Java characters are Unicode characters ¾Unicode is an extension of ASCII), which has thousands of characters (including Latin alphabets, Greek, Cyrillic, Chinese/Japanese/Korean characters, symbols,accents, etc.) ¾java.lang.String is a sequence of Unicode characters, and java.io.Reader and java.io.Writer are streams of Unicode characters ¾If it’s human-readable text, use Unicode; if it’s binary data (like an image) use bytes© Robert Miller 2007 Try/Finally public static void copyStream(Reader from, Writer to)throws IOException {try {char[] buffer = new char[10000];//any size buffer would work, but bigger //performs better while (true) { int n = from.read(buffer); if (n == -1) break; //at the end of the stream to.write(buffer, 0, n); writer.close();}}}} finallyreader.close(); finally clause is run no matter how control leaves the try block –whether by falling out normally or by throwing an exception {© Robert Miller 2007 Reading and Writing Streams /* * Copies all data from the "from" stream to * the "to" stream, then closes both streams. * Throws IOException if any error occurs.*/public static void copyStream(Reader from, Writer to) throws IOException { char[] buffer = new char[10000]; //any size buffer would work, but bigger //performs better while (true) {int n = from.read(buffer); if (n == -1) break; //“from” stream is done to.write(buffer, 0, n);}reader.close();writer.close();© Robert Miller 2007 } It’s important to close the streams to mark the end of the stream and free up resources. But will the streams always be closed in this code? Overloading a Method public static String fetch(String urlString) throws MalformedURLException, IOException { URL(urlString); URL url = new return fetch(url); Overloaded methods } public static String fetch(URL url)throws IOException {//open a connection to the web server InputStream input = url.openStream(); InputStreamReader reader = new InputStreamReader(input); Overloaded methods have the same name but different number or types of arguments ... } Java automatically chooses which overloaded method to call based on the types of the arguments you give it fetch(“http://www.mit.edu”); fetch(new URL(“http://www.mit.edu”));© Robert Miller 2007 3 Java automatically chooses which overloaded method to call based on the  types of the arguments you give it finally clause is run no matter how  control leaves the try block – whether  by falling out normally or by throwing  an exception ate U u fetch(this A Class Representing Web Pages public class Page {private URL url;private String content;public Page(String urlString) throws MalformedURL... fields are variables stored in the object { this.url = new URL(urlString); this.content = Web. constructors create new objects .url); } public URL getURL() { public String getContent() {return this.content;}}return this.url;} getContentmethods are functions that act on an object () this refers to the object itself in a method or constructor © Robert Miller 2007 Final Another way to control changes to a field ¾Fields and variables marked final may not be reassigned after initialization ¾So Page could be kept immutable even if it’s public public final URL url; ¾It’s good practice to use final for any variable that shouldn’t be reassigned (even local variables) public static String fetch(final String urlString) throws ... { final URL url = new URL(urlString);final InputStream input = url.openStream(); final InputStreamReader reader = new InputStreamReader(input); final StringWriter writer = new StringWriter(); ... } © Robert Miller 2007 Access Control ¾public can be used anywhere in the program public URL getURL() ¾private can be used only in this class private URL urlp Access control provides greater safety ¾We want Page to be immutable (never changes once created). What if its fields were public? public URL url; ¾Then it would be possible to change the field anywhere in the program,and Page would no longer be immutablePage p = new Page(“http://www.mit.edu”) p.url = new URL(“http://www.google.com”); ¾With private, it’s much easier to guarantee that the url is never changed © Robert Miller 2007 Caching Pages Web browsers store downloaded pages in a cache ¾So that they don’t have download the page each time it’s used¾Let’s add a cache to the Page class/* Returns the cached Page object for url, /* Stores page in the cache. */private static void putPageInCache(Page page) { ... } or null if no such Page in the cache. */private static Page getPageFromCache(URL url) { ... } Returning an invalid value (like null) is one way to signal an error condition. How else could we have designed this method to signal an error to its caller? © Robert Miller 2007 4 constructors create new objects fields are variables stored in  the object methods are functions that  act on an object this refers to the object itself in a method or constructor Returning an invalid value (like null) is one  way to signal an error condition.  How else  could we have designed this method to  signal an error to its caller?Static Fields and Methods ¾Fields and methods declared static are associated with the class itself,rather than an individual object• A static field has only one value for the whole program (rather than one value per object) – All objects of the class share that single copy of the static field • A static method has no this object • Static methods and fields are referenced using the class name (e.g. Web.fetch()) rather than an object variable • Some classes are purely containers for static code (e.g. Hailstone,Web, java.lang.Math), and no objects of the class are ever constructed¾Fields and methods not declared static are called instance fields ormethods¾static final is commonly used for constants, e.g.:public static final PI = 3.14159; © Robert Miller 2007 Using the Cache public Page(URL url) throws IOException { this.url = url; Page p = getPageFromCache(url); if (p != null) { this.content = p.content; } else { this.content = Web.fetch(url); putPageInCache(this); }}Implementing the Cache private static final Page[] cache = new Page[100];private static int cachePointer = 0; //index of next page to replace in the cache private static Page getPageFromCache(URL url) { for (Page p : cache) { if (p != null && p.getURL().equals(url)) return p; } return null; why might p be null? what happens if we don’t check? //page not found }private static void putPageInCache(Page page) {cache[cachePointer] = page;++cachePointer;if (cachePointer >= cache.length) cachePointer = 0; } © Robert Miller 2007 Summary Exceptions ¾Exceptions are abnormal returns from a method ¾Exceptions can be caught or declared Classes ¾Members (fields, constructors, methods)¾Access control (public, protected, private) ¾Static members¾Overloading© Robert Miller 2007 © Robert Miller 2007 5 why might p be null? what happens if we don’t check?

Description
After completing this lecture notes , you shoul be able to do the following: 1. Describe Exceptions, 2.Classes and 3. Sub classes .
Exceptions are abnormal returns from a method .Exceptions can be caught or declared.In the Classes clearly explained about Members (fields, constructors, methods), Access control (public, protected, private),Static members and Overloading. With the help of examples subclasses are defined.

Instructors: Prof. Daniel Jackson, Prof. Robert Miller MIT Course Number: 6.005 Level: Undergraduate, 6.005 2. Classes More Java: exceptions, input/output, classes, access control, static, 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