TeachJava 2004 - PowerPoint PPT Presentation

1 / 55
About This Presentation
Title:

TeachJava 2004

Description:

Example: Phone Directory ... maintain a directory containing the office address and phone number for each ... in such a directory has a natural representation ... – PowerPoint PPT presentation

Number of Views:37
Avg rating:3.0/5.0
Slides: 56
Provided by: tri5114
Category:

less

Transcript and Presenter's Notes

Title: TeachJava 2004


1
TeachJava! 2004
  • Corky Cartwright
  • Dung Nguyen
  • Stephen Wong
  • James Hsia, Elspeth Simpson, Matthias Ricken, Dan
    Smith

2
From C To Java
  • C and Java have similar syntax.But dont be
    misled!
  • Profoundly different semantics high-level
    objects vs. bytes in memory
  • Profoundly different programming modelsJava is
    object-oriented (OO)C is object-based (OB) in
    normal usage

3
Encouraging Note
  • Writing OO programs in Java is remarkably
    easyprovided we recognize that it is
    fundamentally different than writing OB programs
    in C.
  • There is little common conceptual ground, other
    than syntactic conventions, beween OO programing
    (OOP) in Java and OB programming in C

4
Guiding Vision
  • Program design in Java is data-directed.Design
    the data abstractions first they will determine
    the structure of the code. In OOP circles, this
    data design process is called object-modeling.
  • Common data abstractions are codified as design
    patterns.

5
Secondary Theme
  • DrJava, our lightweight, reactive environment for
    Java, facilitates active learning. With DrJava,
    learning Java is a form of exploration.
  • DrJava is not a toy DrJava is developed using
    DrJava. It includes everything that we believe
    is essential in a programming environment and
    little more.
  • DrJava nows includes support for our programming
    pedagogy in the form of language levels.

6
What Is an Object?
  • Collection of fields representing the properties
    of a conceptual or physical object.
  • Collection of operations called methods for
    observing and changing the fields of the object.
  • These fields and methods often called the
    members of the object.

7
Example Phone Directory
  • Task maintain a directory containing the office
    address and phone number for each person in the
    Rice Computer Science Dept.
  • Each entry in such a directory has a natural
    representation as an object with three fields
    containing a persons
  • name
  • address
  • phone number
  • represented as character strings.

8
Summary of Entry format
  • Fields
  • String name
  • String address
  • String phone
  • Methods
  • String name()
  • String address()
  • String phone()

9
Java Method Invocation
  • A Java method m is executed by sending a method
    call o.m()
  • to an object o, called the receiver. The method
    m must be a member of o.
  • The code defining the method m can refer to the
    receiver using the keyword this.

10
Finger Exercise
  • In the DrJava programming environment, select
    the Elementary Language Level, and enter the
    following class definition
  • class Entry String name String
    address String phone
  • Save this file as Entry.dj0, compile it, and
    type the following statements in the Interactions
    pane
  • Entry e new Entry("Corky","DH 3104","x
    6042") e e.name()
  • e.phone()

11
Java Expressions
  • Java supports essentially the same expressions
    over primitive types (int, float, double,
    boolean) as C.
  • Notable differences
  • boolean is a distinct type from int
  • no unsigned version of integer types
  • explicit long type

12
Finger Exercise
  • Evaluate the following
  • -5 3
  • -(5 3)
  • 5 3
  • 5./3.
  • 5 / 0
  • 5./0.
  • 5
  • 5. 6.

13
Finger Exercise cont.
  • 72. - 32. 1.8
  • (72. - 32.) 1.8
  • 72. - 30. - 12.
  • 72. - (30. - 12.)

14
Java Statements
  • Essentially the same form as in C assignment,
    if, while, for, return,
  • But well-written Java programs consist primarily
    of assignment, if, and return statements (with
    smattering of for).
  • Focus on assignment and if for most of the week.

15
Assignment
  • Restricted form of assignment variable
    definition
  • type var exp
  • Example
  • int x 5

16
Finger Exercise
  • int x 5
  • xx
  • double d .000001
  • double dd dd
  • dd
  • dddd
  • 1. dd
  • 1. dddd

17
Finger Exercise cont.
  • Evaluate
  • int x 7
  • if (x 5) y 0 else y 10
  • y
  • Did you get the behavior that you expected?
    Repeat the exercise with corrected syntax.
  • Evaluate
  • boolean switch1 (x 7)
  • switch1
  • Repeat the exercise with corrected syntax.

18
Classes Object Templates
  • A Java program is a collection of classes.
  • A class is an object template specifying the
    members of each object of the class. These
    members are either fields (values) or methods
    (operations that use the fields of the object).

19
Terminology
  • The methods that return the fields of a class are
    called getters or accessors. In the DrJava
    Elementary language level, the getters for a
    class are generated automatically they have
    exactly the same names as the fields themselves.
  • Instances of a class are creation using the new
    operatornew class-name(arg1, , argn)where
    arg1, , argn are Java expressions giving the
    values of field1, , fieldn

20
Java Data Types
  • Two fundamental categories
  • Primitive types int, boolean, double, float,
    char, long, short, byte (first three are most
    common)
  • Reference types all class instances (objects)
    belong to reference types, which are disjoint
    from the primitive types
  • Values of primitive type (e.g., true, 0) are not
    objects but Java 1.5 automatically converts
    primitive values to corresponding objects and
    vice-versa. The conversion from primitive to
    object form is called auto-boxing. The inverse
    process is called auto-unboxing.

21
Finger Exercises
  • In the Interactions pane, type the following
    codeObject oint x 5xx5o 5oo5
  • Can you devise an expression where using x that
    produces different results from using o? (Let me
    know if you can. Only usage rather than
    modification is allowed.)

22
Reference Types
  • Java classes are organized in a strict hierarchy
    with the universal type Object at the top.
  • Every class C except Object has an immediate
    superclass, which is the parent of C in the
    hierarchy. In a class definition (like our Entry
    example), the default superclass is Object.
  • A descendant in the class hierarchy is called a
    subclass. B is a subclass of A iff A is a
    superclass of B. Entry is a subclass of Object
    Object is a superclass of Entry .
  • Each class C has an associated type (also called
    C) consisting of all instances of the class C and
    its subclasses. Hence, A subclass B
    ? type A ? type B

23
null
  • There is a special value null of every reference
    type on which method invocation utterly fails.
  • null is a reference to nothing the method
    invocation
  • null.m()
  • always generates a NullPointerException aborting
    execution.
  • Finger Exercise try evaluating
  • null.equals(null)

24
Example the String class
  • The String class is built-in to Java, just like
    Object.
  • Finger Exercise evaluate
  • String s "Corky"
  • Object o s
  • o
  • o s
  • String t "Cork" "y
  • t s
  • s.length()
  • o null
  • o.length()
  • Morals
  • multiple copies of the same String may exist do
    not use to test String equality.
  • Do not use null to represent legitimate data
    values.

25
Reference Types cont.
  • Each subclass C inherits (includes) all of the
    members of its superclass.
  • The declared members of C augment the inherited
    members with one exception if C declares a
    method m with exactly the same name and types as
    an inherited method, then the new definition of m
    overrides (replaces) the inherited definition.

26
Inheritance from Object
  • The Object class has several members that its
    children inherit. They include the methods
  • public String toString() which gives a String
    representation for the object.
  • public boolean equals(Object o) which compares
    this to o
  • Note the toString() class can generally be
    ingored at the Elementary language level since it
    is automatically overridden in each class that
    your define to give sensible results.

27
Example of Overriding
  • class Entry
  • String name
  • String address
  • String phone
  • / overridden methods /
  • public String toString()
  • return "" name " ," address " ,"
    phone ""

28
Finger Exercise
  • Open your Entry class into the DrJava
    Interactions pane.
  • Compile your program and evaluate
  • Entry e new Entry("Corky", "DH 3104", "x
    6042") e
  • Add the definition of toString() from the
    previous slide to your Entry class.
  • Compile your program and evaluate
  • Entry e new Entry("Corky", "DH 3104", "x
    6042") e

29
Adding a Method Definition
  • class Entry
  • / return true if the name of "this" matches
    keyName otherwise return false /
  • boolean match(String keyName)
  • return keyName.equals(name)
  • Finger Exercise Add this method definition to
    your Entry class, compile it, and evaluate
  • Entry e new Entry("Corky", "DH 3104", "x
    6042") e.match("Corky")
  • e.match("Matthias")

30
The Wrapper Classes
  • How do we treat primitive values as objects?
    Java includes a built-in wrapper class for each
    primitive type.
  • Examples
  • Integer is the wrapper class for int
  • Boolean is the wrapper class for boolean
  • Double is the wrapper class for double
  • Ignore this issue for now, because auto-boxing
    and auto-unboxing generally make the explicit use
    of wrapper classes unnecessary.

31
Constructors
  • Given a class definition, Java provides a
    mechanism called new for creating new instances
    of the class.
  • To exploit the new, the class must provide a
    special method called a constructor that
    specifies how the fields of the created object
    are initialized.
  • In DrJava, both the Elementary and Intermediate
    language levels automatically generate a
    constructor for each class.
  • A constructor method definition has the same name
    as the class and does not contain the return type
    in the heading.
  • Example
  • Entry(String n, String a, String p)
  • this.name n
  • this.address a
  • this.phone p

32
Union Pattern
  • The union pattern is used to represent different
    forms of related data with some common behavior.
  • The pattern consists of an abstract class A
    together with a collection of variant subclasses
    B1, ..., BN extending A. An abstract class
    cannot be instantiated using new.
  • The collection of classes A, B1, ..., BN is
    called a union hierarchy and A classes is called
    the root class of the hierarchy.
  • The common behavior is codified by a set of
    methods in A, which are usually abstract Each
    such method m has an associated contract that
    that the implementation in each variant class
    must obey.

33
Class Diagram of Union Pattern

34
Defining a Method on a Union
35
City Directory Example
  • Assume that we want to design the data for an
    online city phonebook. In contrast to our
    DeptDirectory example, such a directory will
    contain several different kinds of listings
    businesses, residences, and government agencies.
  • The entry data for such a directory is
    represented by using the union pattern to
    identify the common behavior among the various
    kinds of listings.
  • In this case, the common behavior is the
    existence of a String name for the listing and
    the String text of the listing (given by
    toString()).

36
Definition of CityEntry
  • A CityEntry is either
  • a ResidentialEntry(name,address,phone)
  • a BusinessEntry(name,address,phone,city,state)
  • a GovernmentEntry(name,address,phone,city,
    state, government)
  • Examples
  • ResidentialEntry("Corky Cartwright","3310
    Underwood", "713-660-6967")
  • BusinessEntry("ToysRUs","2101 Old Spanish
    Trail","713-664-1234","Houston", "TX")
  • GovernmentEntry("Federal Drug Administration",
    "800-666-9000", "Washington", "DC", "Federal")

37
Class Diagram of CityEntry Union
38
Defining Methods on Unions
  • Assume that we want to define a method on a
    union. The method will typically require a
    separate implementation for each variant
    (subclass) of the union. But each
    implementation will satisfy the same "contract"
    (description of behavior).
  • In Java, the method must not only be defined in
    each variant of the union, it must be declared as
    abstract in the root class of the union
    hierarchy. Otherwise, Java will not allow the
    method to be invoked on objects of the union type.

39
CityEntry
  • abstract class CityEntry
  • class BusinessEntry extends CityEntry
  • String name, address, phone, city, state
  • class GovernmentEntry extends CityEntry
  • String name, address, phone, city, state,
    government
  • class ResidentialEntry extends CityEntry
  • String name, address, phone, city

40
Finger Exercise
  • Enter the definitions of CityEntry,
    ResidentialEntry, BusinessEntry, GovernmentEntry
    in the Definitions pane of DrJava.
  • Save this program in a file named PhoneBook.dj0.
  • Compile this program and evaluateResidentialEnt
    ry re new ResidentialEntry("Corky
    Cartwright","3310 Underwood", "713-660-6967")re
    .name()BusinessEntry be new
    BusinessEntry("ToysRUs","2101 Old Spanish
    Trail","713-664-1234","Houston",
    "TX")be.name() GovernmentEntry ge new
    GovernmentEntry("Federal Drug Administration",
    "800-666-9000", "Washington", "DC",
    "Federal")ge.name()CityEntry ce
    rece.name()

41
Finger Exercise cont.
  • What went wrong in the evaluation of ce.name()?
  • There is no name method defined for CityEntry.
    Define an abstract method name() in CityEntry,
    recompile your program and repeat the same
    exercise. (Note you can recall previous lines
    that you have typed in the Interactions pane by
    using the ? key.)
  • What methods besides name() should we include in
    the common behavior for CityEntry? address()?
    phone()? city()? state()? government()?
  • Add these other methods to CityEntry. Test them
    in the Interactions pane.

42
Member Hoisting
  • In a union hierarchy, the same code may be
    repeated in every variant.
  • A cardinal rule of software engineering is never
    duplicate code. We can eliminate code
    duplication in a union hierarchy by hoisting
    duplicated code (code that is invariant within
    the union) into the abstract class at the route
    of the hierarchy.

43
CityEntry Example
  • We can hoist the fields name, address, and phone.
    (Note this hoisting transformation is trivial
    in the Elementary and Intermediate language
    levels. In the full Java language, there are
    some annoying additions and modifications that we
    must make to the boilerplate code in the classes
    forming the union pattern.
  • This hoisting process does not affect the form of
    the class diagram.

44
CityEntry II
  • abstract class CityEntry
  • String name, address, phone
  • class BusinessEntry extends CityEntry
  • String city, state
  • class GovernmentEntry extends CityEntry
  • String city, state, government
  • class ResidentialEntry extends CityEntry

45
Partial Hoisting
  • In a union hierarchy, the same code may be
    repeated in some proper subset of the variants.
  • We can eliminate this code duplication by
    introducing a new abstract class that is a
    superclass only of the variants that repeat the
    same code.
  • Partial hoisting modifies the form of the class
    diagram because it introduces a new abstract
    class below the root abstract class of the union.

46
Revised Class Hierarchy
47
CityEntry III
  • abstract class CityEntry
  • String name, address, phone
  • abstract class NonResidentialEntry extends
    CityEntry
  • String city, state
  • class BusinessEntry extends NonResidentialEntry
  • class GovernmentEntry extends CityEntry
  • String government
  • class Residential Entry extends CityEntry

48
A DeptDirectory cont.
  • Defining DeptDirectory Data
  • A DeptDirectory is either
  • Empty(), the empty DeptDirectory , or
  • NonEmpty(first,rest), a non-empty DeptDirectory,
    where first is an Entry and rest is a
    DeptDirectory
  • Examples
  • Empty()NonEmpty(Entry("Stephen","DH 3103","x
    3846"), Empty())

49
Class Diagram for DeptDirectory
50
DeptDirectory
abstract class DeptDirectory class Empty
extends DeptDirectory class Cons extends
DeptDirectory Entry first DeptDirectory
rest
51
The Composite Pattern
  • The DeptDirectory class hierarchy is a special
    form of union called a composite. A union is
    composite when one or more variants contain
    fields of the root class type. In other words,
    variants in the union contain references to
    objects of union type. In the DeptDirectory
    example, the NonEmpty variant contains a field
    rest of type DeptDirectory.

52
Searching a DeptDirectory
  • Given the name of a person, we want to find that
    person's phone number in our DeptDirectory. In
    other words, we want to define a method on the
    DeptDirectory class
  • findAddress(String keyName)
  • that searches "this" DeptDirectory for an Entry
    that matches the argument keyName.

53
The Interpreter Pattern
  • To define a method m on a composite class like
    DeptDirectory, we follow the same process as we
    would in defining a method on a union class, with
    one new wrinkle. In the variants that refer to
    the composite class (have fields of composite
    class type), computing m for this will usually
    involve delegating the task of computing m for
    the embedded references to the composite class.
  • In our DeptDirectory example, the only embedded
    reference to DeptDirectory in variant subclasses
    is the rest field in NonEmpty.

54
Template for coding findPhone
  • abstract class DeptDirectory
  • abstract String findPhone(String key)
  • class Empty extends DeptDirectory
  • String findPhone(String key)
  • class Cons extends DeptDirectory
  • Entry first
  • DeptDirectory rest
  • String findPhone(String key)
  • rest.findPhone(key)

Fill in this method body
Fill in this method body
55
findPhone
  • abstract class DeptDirectory
  • abstract String findPhone(String key)
  • class Empty extends DeptDirectory
  • String findPhone(String key) return null
  • class NonEmpty extends DeptDirectory
  • Entry first
  • DeptDirectory rest
  • String findPhone(String key)
  • if (key.equals(first.name()))
  • return first.phone()
  • else return rest.phone(key)
Write a Comment
User Comments (0)
About PowerShow.com