DOC PREVIEW
Berkeley COMPSCI 61B - Object-Oriented Mechanisms

This preview shows page 1 out of 4 pages.

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

Unformatted text preview:

CS61B Lecture #8: Object-Oriented MechanismsOverloadingGeneric Data StructuresDynamic vs. Static TypesType HierarchiesThe Basic Static Type RuleConsequences of Compiler's ``Sanity Checks''Overriding and ExtensionOverriding toStringExtending a ClassIllustrationWhat About Fields and Static Methods?What's the Point?CS61B Lecture #8: Object-Oriented MechanismsReadings for Lab: Scan the on-line Javadoc documentation for List,ArrayList, LinkedList, Iterator, ListIterator, Set, TreeSet, in the java.utilpackage.Readings for Wednesday: Chapters 8 and 9 ofHead-First JavaToday:• New in this lecture: the bare mechanics of “object-oriented pro-gramming.”• The general topic is: Writing software that operates on many kindsof data.Last modified: Mon Sep 14 12:16:42 2009 CS61B: Lecture #8 1OverloadingProblem: How to get System.out.print(x) to print x, regardless oftype of x?• In Scheme, one function can take an argument of any type, and thentest the type.• In Java, methods specify a single type of argument.• Partial solution:overloading—multiple method definitions with thesame name and different numbers or types of arguments.• E.g., System.out has type java.io.PrintStream, which definesvoid println()Prints new line.void println(String s)Prints S.void println(boolean b)Prints "true" or "false"void println(char c)Prints single charactervoid println(int i)Prints I in decimaletc.• Each of these is a different function. Compiler decides which to callon the basis of arguments’ types.Last modified: Mon Sep 14 12:16:42 2009 CS61B: Lecture #8 2Generic Data StructuresProblem: How to get a “list of anything” or “array of anything”?• Again, no problem in Scheme.• But in Java, lists (such as IntList) and arrays have a single type ofelement.• First, the short answer: any reference value can be converted totype java.lang.Object and back, so can use Object as the “generic(reference) type”:Object[] things = new Object[2];things[0] = new IntList (3, null);things[1] = "Stuff";// Now ((IntList) things[0]).head == 3;// and ((String) things[1]).startsWith("St") is true//things[0].head Illegal// things[1].startsWith ("St") IllegalLast modified: Mon Sep 14 12:16:42 2009 CS61B: Lecture #8 3Dynamic vs. Static Types• Everyvaluehas a type—itsdynamic type.• Everycontainer(variable, component, parameter), literal, functioncall, and operator expression (e.g. x+y) has a type—itsstatic type.• Therefore, everyexpressionhas a static type.Object[] things = new Object[2];things[0] = new IntList (3, null);things[1] = "Stuff";things:Object[] Object ObjectObject[]Object[]3IntList"Stuff"Stringint <nulltype>IntListint IntListString???static typecontainerdynamic typevalueLast modified: Mon Sep 14 12:16:42 2009 CS61B: Lecture #8 4Type Hierarchies• A container with (static) type T may contain a certain value only ifthat value “is a” T—that is, if the (dynamic) type of the value is asubtypeof T. Likewise, a function with return type T may returnonly values that are subtypes of T.• All types are subtypes of themselves (& that’s all for primitive types)•Reference typesform atype hierarchy;some are subtypes of oth-ers. null’s type is a subtype of all reference types.• All reference types are subtypes of Object.int double boolean ... ObjectInteger Double Boolean String IntList int[] Object[] ...String[]<nulltype>is a(un)wraps toLast modified: Mon Sep 14 12:16:42 2009 CS61B: Lecture #8 5The Basic Static Type Rule• Java is designed so that any expression of (static) type T alwaysyields a value that “is a” T.• Static types are “known to the compiler,” because you declare them,as inString x; // Static type of fieldint f (Object s) { // Static type of call to f, and of parameterint y; // Static type of local variableor they are pre-declared by the language (like 3).• Compiler insists that in anassignment,L = E, or function call, f(E),wherevoid f (SomeType L) { ... },E’s static type must be subtype of L’s static type.• Similar rules apply to E[i] (static type of E must be an array) andother built-in operations.• Slight fudge: compiler willcoerce“smaller” integer types to largerones, float to double, and (from last lecture) between primitivetypes and their wrapper types.Last modified: Mon Sep 14 12:16:42 2009 CS61B: Lecture #8 6Consequences of Compiler’s “Sanity Checks”• This is aconservativerule. The last line of the following, which youmight think is perfectly sensible, is illegal:int[] A = new int[2];Object x = A; // All references are ObjectsA[i] = 0; // Static type of A is array...x[i+1] = 1; // But not of x: ERRORCompiler figures that not every Object is an array.• Q: Don’t weknowthat x contains array value!?• A: Yes, but still must tell the compiler, like this:((int[]) x)[i+1] = 1;• Defn: Static type of cast (T) E is T.• Q: What if xisn’tan array value, or is null?• A: For that we have runtime errors—exceptions.Last modified: Mon Sep 14 12:16:42 2009 CS61B: Lecture #8 7Overriding and Extension• Notation so far is clumsy.• Q: If I know Object variable x contains a String, why can’t I write,x.startsWith("this")?• A: startsWith is only defined on Strings, not on all Objects, so thecompiler isn’t sure it makes sense, unless you cast.• But, if an operationweredefined on all Objects, then youwouldn’tneed clumsy casting.• Example: .toString() is defined on all Objects. You can always sayx.toString() if x has a reference type.• The default .toString() function is not very useful; on an IntList,would produce string like "IntList@2f6684"• But for any subtype of Object, you mayoverridethe default defi-nition.Last modified: Mon Sep 14 12:16:42 2009 CS61B: Lecture #8 8Overriding toString• For example, if s is a String, s.toString() is the identity function(fortunately).• For any type you define, you may supply your own definition. Forexample, in IntList, could addpublic String toString () {StringBuffer b = new StringBuffer ();b.append ("[");for (IntList L = this; L != null; L = L.tail)b.append (" " + L.head);b.append ("]");return b.toString ();}• If x = new IntList (3, new IntList (4, null)), then x.toString()is "[3 4]".• Conveniently, the "+" operator on Strings calls .toString when askedto append an Object, and so does the "%s" formatter for printf.• With this trick, you can supply an output function for any type youdefine.Last modified: Mon Sep 14 12:16:42 2009 CS61B: Lecture #8 9Extending a Class• To say


View Full Document

Berkeley COMPSCI 61B - Object-Oriented Mechanisms

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 Object-Oriented Mechanisms
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 Object-Oriented Mechanisms 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 Object-Oriented Mechanisms 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?