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 MechanismsPublic Service Announcement:• CalSol, the UC Berkeley solar car team, is looking for new members.• Preferably in MechE and EECS, but all welcome.• See their web site, www.me.berkeley.edu/calsol, for more.Readings:• Chapter 2, “Values, Types, and Containers,” inAssorted Notes onJava(in the reader).• Chapters 7 and 8 inHead First Java.Today:• New in this lecture: the bare mechanics of “object-oriented pro-gramming.”• The general topic is: Writing s oftwa re that operates on ma ny kindsof data.Last modified: Fri Feb 3 13:19:05 2006 CS61B: Lecture #8 1OverloadingProblem: How to get System.out.p rint(x) or stdout.put (x) to printx, regardless of type of x?• In Scheme, one function can take an arg ume nt 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 typ e 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 thes e is a different function. Compiler decide s which to callon the basis of arguments’ types.Last modified: Fri Feb 3 13:19:05 2006 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 re ference value can be converted totype java.lang.Ob ject and back, so can use Object a s 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: Fri Feb 3 13:19:05 2006 CS61B: Lecture #8 3Dynamic vs. Static Types• Everyvaluehas a type—itsdynamic type.• Everycontainer(variable, component, parameter ) , liter al, 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: Fri Feb 3 13:19:05 2006 CS61B: Lecture #8 4Type Hierarchies• A container with (static) typ e 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 typ es 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: Fri Feb 3 13:19:05 2006 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 ty pe 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 (SomeTyp e 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: compil er willcoerce“smaller” integer typ es to largerones, floa t to double, and (from last lecture) between primitivetypes and their wrapper types.Last modified: Fri Feb 3 13:19:05 2006 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 referenc es 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: Fri Feb 3 13:19:05 2006 CS61B: Lecture #8 7Overriding and Extension• Notation so far is clumsy.• Q: If I know Object vari a bl e x contains a String, why can’t I write,x.startsWith("this")?• A: star tsWith 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 Obj ects, then youwouldn’tneed clumsy casting.• Example: .toString() is defined on all Objects. You can al ways sayx.toString() i f 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: Fri Feb 3 13:19:05 2006 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, as wedid in class IntList:public 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.toStr i ng ();}• If x = new IntList (3, new IntList (4, null)), then x.toStrin g()is "[3 4]".• Conveniently, the "+" opera tor on Strings calls .toString w hen askedto append an Object, and so does the "%s"


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?