DOC PREVIEW
Berkeley COMPSCI 61B - Lecture Notes

This preview shows page 1-2 out of 6 pages.

Save
View full document
View full document
Premium Document
Do you want full access? Go Premium and unlock all 6 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 6 pages.
Access to all documents
Download any document
Ad free experience
Premium Document
Do you want full access? Go Premium and unlock all 6 pages.
Access to all documents
Download any document
Ad free experience

Unformatted text preview:

CS61B Lectures #7--8: Abstract Methods and ClassesConcrete SubclassesInterfacesInterface SyntaxMultiple InheritanceReview: Higher-Order FunctionsMap in JavaA PuzzleAnswer to PuzzleExample: Designing a ClassSpecification Seen by ClientsHistogram SpecificationAn ImplementationImplementation continuesLet's Make a Tiny ChangeImplementing the Tiny ChangeSketch of Changes for New ImplementationAdvantages of Procedural InterfaceWhat to do About Errors?Catching ExceptionsCS61B Lectures #7–8:Public Service Announcement. HKN (Eta Kappa Nu), with offices in290 Cory and 345 Soda, URL: http://hkn.berkeley.edu. Offers• Free Drop-In Tutoring M-F 10-4• Exam Files (online and in offices for check out)New Lab Turn-in Policy.• Please have your lab ready at the beginning of the lab period in theweek its due. So, have the lab results due next Tuesday ready atthestartof that lab.• TAs will do check-offs “randomly” starting at the beginning of labfor the students in that lab section.• Therefore, make sure that you’ve cleared “official” membership inwhatever lab section you attend with your TA.• The idea is to encourage everyone to be working on the same lab atthe same time, and not to fall behind.• If you have a problem for some reason, please discuss it with yourTAin advance.Last modified: Sun Sep 15 17:25:54 2002 CS61B: Lectures #7–8 1Abstract Methods and Classes• Instance method can beabstract:No body given; must be suppliedin subtypes.• One good use is in specifying a pure interface to a family of types:/** A drawable object. */public abstract class Drawable { // "abstract" = "can’t say new Drawable"/** Expand THIS by a factor of SIZE */public abstract void scale (double size);/** Draw THIS on the standard output. */public abstract void draw ();}Now a Drawable is something that hasat leastthe operations scaleand draw on it. Can’t create a Drawable because it’s abstract—inparticular, it has two methods without any implementation.•BUT,we can write methods that operate on Drawables:void drawAll (Drawable[] thingsToDraw) {for (int i = 0; i < thingsToDraw.length; i += 1)thingsToDraw[i].draw ();}• But draw has no implementation! How can this work?Last modified: Sun Sep 15 17:25:54 2002 CS61B: Lectures #7–8 2Concrete Subclasses• Can define kinds of Drawables that are non-abstract. To do so, mustsupply implementations for all methods:public class Rectangle extends Drawable {public Rectangle (double w, double h) { this.w = w; this.h = h; }public void scale (double size) { w *= size; h *= size; }public void draw () {draw awxhrectangle}private double w,h;}public class Circle extends Drawable {public Circle (double rad) { this.rad = rad; }public void scale (double size) { rad *= size; }public void draw () {draw a circle with radiusrad }double rad;}Any Circle or any Rectangle is a Drawable.• So, writingDrawable[] things = { new Rectangle (3, 4), new Circle (2) };drawAll (things);draws a 3 × 4 rectangle and a circle with radius 2.Last modified: Sun Sep 15 17:25:54 2002 CS61B: Lectures #7–8 3Interfaces• In generic use, aninterfaceis a “point where interaction occursbetween two systems, processes, subjects, etc.” (Concise OxfordDictionary).• In programming, often use the term to mean adescriptionof thisgeneric interaction.• Specifically, a description of the functions or variables by which twothings interact• Java uses the term to refer to a slight variant of an abstract classthat contains only abstract methods (and static constants).• Idea is to treat Java interfaces as the public specifications of datatypes, and classes as theirimplementations.Last modified: Sun Sep 15 17:25:54 2002 CS61B: Lectures #7–8 4Interface Syntax• Instead of making Drawable an abstract class, could have writteninstead:public interface Drawable {void scale (double size);void draw ();}public class Rectangleimplements Drawable {...}• Interfaces are automatically abstract (can’t say new Drawable()).• Interface methods are automatically public and abstract.Last modified: Sun Sep 15 17:25:54 2002 CS61B: Lectures #7–8 5Multiple Inheritance• Canextendone class, butimplementany number of interfaces.• Contrived Example:interface Readable { | void copy (Readable r,Object get (); | Writable w) {} | w.put (r.get ());| }interface Writable {void put (Object x);}class Source implements Readable {public Object get () { ... }}class Sink implements Writable {public void put (Object x) { ... }}class Variable implements Readable, Writable {public Object get () { ... }public void put (Object x) { ... }}• The first argument of copy can be a Source or a Variable. Thesecond can be aSink or a Variable.Last modified: Sun Sep 15 17:25:54 2002 CS61B: Lectures #7–8 6Review: Higher-Order Functions• In Scheme, you hadhigher-order functionslike this (adapted fromSICP)(define (map proc items); function list(if (null? items)nil(cons (proc (car items)) (map proc (cdr items)))))and could write(map abs (list -10 2 -11 17))====> (10 2 11 17)(map (lambda (x) (* x x)) (list 1 2 3 4))====>(1 4 9 16)• Java does not have these directly, but can use abstract classes orinterfaces and subtyping to get the same effect (with more writing)Last modified: Sun Sep 15 17:25:54 2002 CS61B: Lectures #7–8 7Map in Java/** A function with one integer argument */public interface Proc1 {int apply (int x);}IntList map (Proc1 proc, IntList items) {if (items == null)return null;else return new IntList (proc.apply (items.head),map (proc, items.tail));}• It’s the use of this function that’s clumsy. First, define class forabsolute value function; then create an instance:class Abs implements Proc1 {public int apply (int x) { return Math.abs (x); }}----------------------------------------------map (new Abs (),some list);• There are lambda expressions (sort of):map (new Proc1 () { public int apply (int x) { return x*x; } },some list);Last modified: Sun Sep 15 17:25:54 2002 CS61B: Lectures #7–8 8A Puzzleclass A {void f () { System.out.println ("A.f"); }void g () { f (); /* =this.f() */ }//static void g (A y) { y.f(); }For question 2}class B extends A {void f () { System.out.println ("B.f"); }}class C {static void main (String[] args) {B aB = new B ();h (aB);}static void h (A x) { x.g() }//static void h (A x) { x.g(x); }For question 2}1. What is printed?2. What if we madeg static (as shown)?3. What iff were made static?4. What iff were not defined in A?Choices:a.A.fb. B.fc. Some kind of errorLast


View Full Document

Berkeley COMPSCI 61B - Lecture Notes

Documents in this Course
Lab

Lab

4 pages

Matrix

Matrix

3 pages

Numbers

Numbers

14 pages

Lectures

Lectures

12 pages

Project 1

Project 1

24 pages

Exam

Exam

8 pages

Load more
Download Lecture Notes
Our administrator received your request to download this document. We will send you the file to your email shortly.
Loading Unlocking...
Login

Join to view Lecture Notes and access 3M+ class-specific study document.

or
We will never post anything without your permission.
Don't have an account?
Sign Up

Join to view Lecture Notes 2 2 and access 3M+ class-specific study document.

or

By creating an account you agree to our Privacy Policy and Terms Of Use

Already a member?