Docsity

Java and Java Generics in CMSC 330: Subtyping, Polymorphism, and Parametric Polymorphism, Study notes of Programming Languages

Toggle sidebar
bg1
1
CMSC 330: Organization of
Programming Languages
Java and Java Generics
CMSC 330 2
Java
• Developed in 1995 by Sun Microsystems
– Started off as Oak, a language aimed at software for
consumer electronics
– Then the we b came along...
• Java incorporated into web browsers
– Java source code compiled into Java byte code
– Executed (inter preted) on Java Virtual Machine
• Portability to different platforms
• Safety and security m uch easier, because code is not
directly executing on har dware
• These days, Java used for a lot of purposes
– Server s ide programming, general pl atform, etc.
CMSC 330 3
Java Versions
• Java has evolved over the years
– Virtual m achine quite stable, but source language
has been getting new features
• Will use the latest version of Java for this class
– If you’ve got an older version, you mi ght want to
upgrade
CMSC 330 4
Subtyping
• Both inheritance and interfaces allow one class
to be used where another is specified
– This is r eally the same idea: subtyping
• We say that Ais a subtype of Bif
–Aextends Bor a subtype of B, or
–Aimplements Bor a subtype of B
CMSC 330 5
Liskov Substitution Principle
If for each object o1 of type Sthere is an object o2 of
type Tsuch that for all programs Pdefined in terms of T,
the behavior of Pis unchanged when o1 is substituted for
o2 then Sis a subtype of T.
– I.e, if an yone expecting a Tcan be given an S, then
Sis a subtype of T.
– Does our def inition of subtyping in terms of extends
and implements obey this principl e?
CMSC 330 6
Polymorphism
• Subtyping is a kind of polymorphism
– Sometimes called subtype polymorphism
– Allows method to accept objects of many types
•We saw parametric polymorphism in OCaml
– It’s pol ymorphism because polymorphic functions can
be applied to many different types
•Ad-hoc polymorphism is overloading
– Operator over loading in C++
– Method overl oading in Java
pf3
pf4
pf5

Partial preview of the text

Download Java and Java Generics in CMSC 330: Subtyping, Polymorphism, and Parametric Polymorphism and more Study notes Programming Languages in PDF only on Docsity!

CMSC 330: Organization of

Programming Languages

Java and Java Generics

CMSC 330 2

Java

  • Developed in 1995 by Sun Microsystems
    • Started off as Oak, a language aimed at software for

consumer electronics

  • Then the web came along...
  • Java incorporated into web browsers
  • Java source code compiled into Java byte code
  • Executed (interpreted) on Java Virtual Machine
  • Portability to different platforms
  • Safety and security much easier, because code is not directly executing on hardware
  • These days, Java used for a lot of purposes
  • Server side programming, general platform, etc.

CMSC 330 3

Java Versions

  • Java has evolved over the years
    • Virtual machine quite stable, but source language

has been getting new features

  • Will use the latest version of Java for this class
    • If you’ve got an older version, you might want to

upgrade

CMSC 330 4

Subtyping

  • Both inheritance and interfaces allow one class

to be used where another is specified

  • This is really the same idea: subtyping
  • We say that A is a subtype of B if
  • A extends B or a subtype of B, or
  • A implements B or a subtype of B

CMSC 330 5

Liskov Substitution Principle

If for each object o1 of type S there is an object o2 of type T such that for all programs P defined in terms of T, the behavior of P is unchanged when o1 is substituted for o2 then S is a subtype of T.

  • I.e, if anyone expecting a T can be given an S, then

S is a subtype of T.

  • Does our definition of subtyping in terms of extends

and implements obey this principle?

CMSC 330 6

Polymorphism

  • Subtyping is a kind of polymorphism
    • Sometimes called subtype polymorphism
    • Allows method to accept objects of many types
  • We saw parametric polymorphism in OCaml
    • It’s polymorphism because polymorphic functions can

be applied to many different types

  • Ad-hoc polymorphism is overloading
    • Operator overloading in C++
    • Method overloading in Java

CMSC 330 7

Polymorphism Using Object

class Stack { class Entry { Object elt; Entry next; Entry(Object i, Entry n) { elt = i; next = n; } } Entry theStack; void push(Object i) { theStack = new Entry(i, theStack); } Object pop() throws EmptyStackException { if (theStack == null) throw new EmptyStackException(); else { Object i = theStack.elt; theStack = theStack.next; return i; }}}

CMSC 330 8

Stack Client

Stack is = new Stack(); Integer i; is.push(new Integer(3)); is.push(new Integer(4)); i = (Integer) is.pop();

  • Now Stacks are reusable
    • push() works the same
    • But now pop() returns an Object
      • Have to downcast back to Integer
      • Not checked until run-time

CMSC 330 9

General Problem

  • When we move from an X container to an

Object container

  • Methods that take X’s as input parameters are OK
    • If you’re allowed to pass Object in, you can pass any X in
  • Methods that return X’s as results require downcasts
    • You only get Objects out, which you need to cast down to X
  • This is a general feature of subtype

polymorphism

CMSC 330 10

Parametric Polymorphism (for Classes)

  • In Java 1.5 we can parameterize the Stack

class by its element type

  • Syntax:
    • Class declaration: class A { ... }
      • A is the class name, as before
      • T is a type variable , can be used in body of class (...)
    • Client usage declaration: A x;
      • We instantiate A with the Integer type

CMSC 330 11

class Stack { class Entry { ElementType elt; Entry next; Entry(ElementType i, Entry n) { elt = i; next = n; } } Entry theStack; void push(ElementType i) { theStack = new Entry(i, theStack); } ElementType pop() throws EmptyStackException { if (theStack == null) throw new EmptyStackException(); else { ElementType i = theStack.elt; theStack = theStack.next; return i; }}}

Parametric Polymorphism for Stack

CMSC 330 12

Stack Client

Stack is = new Stack(); Integer i; is.push(new Integer(3)); is.push(new Integer(4)); i = is.pop();

  • No downcasts
  • Type-checked at compile time
  • No need to duplicate Stack code for every usage
    • line i = is.pop(); can stay the same even if the type of is isn’t an integer in every path through the program

CMSC 330 19

Subtyping and Arrays

  • Java has one funny subtyping feature:
    • If S is a subtype of T, then
    • S[] is a subtype of T[]
  • Lets us write methods that take arbitrary arrays

public static void reverseArray(Object [] A) { for(int i=0, j=A.length-1; i<j; i++,j--) { Object tmp = A[i]; A[i] = A[j]; A[j] = tmp; } }

CMSC 330 20

Problem with Subtyping Arrays

  • Program compiles without warning
  • Java must generate run-time check at (1) to prevent (2)
    • Type written to array must be subtype of array contents

public class A { ... } public class B extends A { void newMethod(); } ... void foo(void) { B[] bs = new B[3]; A[] as;

as = bs; // Since B[] subtype of A[] as[0] = new A(); // (1) bs[0].newMethod(); // (2) Fails since not type B }

CMSC 330 21

Subtyping for Generics

  • Is Stack a subtype of Stack?
    • We could have the same problem as with arrays
    • Thus Java forbids this subtyping
  • Now consider the following method:
    • Not allowed to call count(x) where x has type
  • Stack

    int count(Collection c) { int j = 0; for (Iterator i = c.iterator(); i.hasNext(); ) { Object e = i.next(); j++; } return j; }

    CMSC 330 22

    int count(Collection c) { int j = 0; for (Iterator i = c.iterator(); i.hasNext(); ) { T e = i.next(); j++; } return j;}

    Solution I: Use Polymorphic Methods

    • But requires a “dummy” type variable that isn’t

    really used for anything

    CMSC 330 23

    Solution II: Wildcards

    • Use? as the type variable
      • Collection<?> is “Collection of unknown”
    • Why is this safe?
      • Using? is a contract that you’ll never rely on having a

    particular parameter type

    • All objects subtype of Object, so assignment to e ok

    int count(Collection<?> c) { int j = 0; for (Iterator<?> i = c.iterator(); i.hasNext(); ) { Object e = i.next(); j++; } return j; }

    CMSC 330 24

    Legal Wildcard Usage

    • Reasonable question:
      • Stack is not a subtype of Stack
      • Why is Stack a subtype of Stack<?>?
      • Answer:
        • Wildcards permit “reading” but not “writing”
      • CMSC 330 25

        Example: Can read but cannot write

        int count(Collection<?> c) { int j = 0; for (Iterator<?> i = c.iterator(); i.hasNext(); ) { Object e = i.next(); c.add(e); // fails: Object is not? j++; } return j; }

        CMSC 330 26

        For Loops

        • Java 1.5 has a more convenient syntax for this

        standard for loop

        • This loop will get the standard iterate and set e to

        each element of the list, in order

        int count(Collection<?> c) { int j = 0; for (Object e : c) j++; return j; }

        CMSC 330 27

        More on Generic Classes

        • Suppose we have classes Circle, Square, and

        Rectangle, all subtypes of Shape

        • Can we pass this method a Collection?
          • No, not a subtype of Collection
        • How about the following?

        void drawAll(Collection c) { for (Shape s : c) s.draw(); }

        void drawAll(Collection<?> c) { for (Shape s : c) s.draw(); }

        // not allowed, assumes? is Shape CMSC 330 28

        Bounded Wildcards

        • We want drawAll to take a Collection of anything

        that is a subtype of shape

        • this includes Shape itself
        • This is a bounded wildcard
        • We can pass Collection
        • We can safely treat e as a Shape

        void drawAll(Collection<? extends Shape> c) { for (Shape s : c) s.draw(); }

        CMSC 330 29

        Upper Bounded Wild Cards

        -? extends Shape actually gives an upper bound

        on the type accepted

        • Shape is the upper bound of the wildcard

        Shape

        Circle

        Rectangle

        Square

        CMSC 330 30

        Bounded Wildcards (cont’d)

        • Should the following be allowed?
          • No, because c might be a Collection of something

        that is not compatible with Circle

        • This code is forbidden at compile time

        void foo(Collection<? extends Shape> c) { c.add(new Circle()); }