DOC PREVIEW
Berkeley COMPSCI 61B - Objects: Inheritance, Overriding Methods

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 #6: Objects: Inheritance, Overriding MethodsOverloadingGeneric 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 #6: Objects: Inheritance, OverridingMethods• Discussion section 118 (Th1-2) moved to 405 Soda.• Discussion section 119 (Th2-3) moved to 2 Evans.• Reading for today:PIJ1.11-1.12.• Reading for Wednesday:PIJrest of Chapter 1.• New in this lecture: the bare mechanics of “object-oriented pro-gramming”Last modified: Mon Sep 9 01:28:29 2002 CS61B: Lecture #6 1OverloadingProblem: How to get System.out.print(x) or stdout.put(x) to printx, regardless of type 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 argument types (or numbers).• 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 9 01:28:29 2002 CS61B: Lecture #6 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 totypejava.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") Illegal• (Primitive types? Sorry; they blew it—primitive value is not an Ob-ject, but can usewrapper typesInteger, Double, . . . , from theJava library. E.g.,new Integer(3) is an object whose .intValue()method extracts the 3.)Last modified: Mon Sep 9 01:28:29 2002 CS61B: Lecture #6 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 9 01:28:29 2002 CS61B: Lecture #6 4Type Hierarchies• A container with (static) type T may contain a certain value only ifthat value “is a” T—if the (dynamic) type of the value is asubtypeof T. Likewise, a function with return type T may return only valuesthat are subtypes of T.• Java is designed so that any expression of (static) type T alwaysyields a value that “is a” 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 ... ObjectString IntList Object[] int[] ...String[]<nulltype>is aLast modified: Mon Sep 9 01:28:29 2002 CS61B: Lecture #6 5The Basic Static Type Rule• Static types are “known to the compiler,” because you declare them,as inObject 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.Last modified: Mon Sep 9 01:28:29 2002 CS61B: Lecture #6 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 9 01:28:29 2002 CS61B: Lecture #6 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 only defined on Strings, not on all Objects, so com-piler isn’t sure it makes sense, unless you cast.• But, if an operationweredefined on all Objects, then youwouldn’tneed clumsy casting.• Example: .toString() defined on all Objects. You can always sayx.toString() if x has a reference type.• The default .toString() function not very useful; on an IntList,would produce string like"IntList@2f6684"•But for any subtype of Object, mayoverridethe default definition.Last modified: Mon Sep 9 01:28:29 2002 CS61B: Lecture #6 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:class IntList {...existing stuff...public String toString () {return "(" + head + "," + tail + ")";} // Note: "+ tail" appends null or} // tail.toString(), as appropriate•If x = new IntList (3, new IntList (4, null)), then x.toString()is "(3,(4,null))".• Conveniently, the "+" operator on Strings calls .toString when askedto append an Object.• With this trick, you can supply an output function for any type youdefine.Last modified: Mon Sep 9 01:28:29 2002 CS61B: Lecture #6 9Extending a Class• To say that class B is a subtype of class A (or A is asuperclassof B,writeclass B extends A { ... }• By default, class ... extends java.lang.Object.• The subtypeinheritsall


View Full Document

Berkeley COMPSCI 61B - Objects: Inheritance, Overriding Methods

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 Objects: Inheritance, Overriding Methods
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 Objects: Inheritance, Overriding Methods 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 Objects: Inheritance, Overriding Methods 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?