Docsity

Java and Java Generics: Inheritance, Subtyping, Polymorphism, and Inner Classes - Prof. Je, Study notes of Programming Languages

Toggle sidebar
bg1
1
CMSC 433: Programming
Paradigms and Technologies
Fall 2008
Java and Java Generics
(slides partially developed by Jeff Foster)
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. 2
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14

Partial preview of the text

Download Java and Java Generics: Inheritance, Subtyping, Polymorphism, and Inner Classes - Prof. Je and more Study notes Programming Languages in PDF only on Docsity!

CMSC 433: Programming

Paradigms and Technologies

Fall 2008

Java and Java Generics

(slides partially developed by Jeff Foster)

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. 2

Java Versions

• Java has evolved over the years

– Virtual machine quite stable, but source language

has been getting new features

• New features added to Java 1.5 (a.k.a Java 5.0)

– Some of the new features in Java 1.5 came as a

response to pressure from Microsoft’s C#

3 4

Object-Orientation

• Java is a class-based, object-oriented language

• Classes extend other classes to inherit

– The root of the inheritance hierarchy is Object

– Why have a root of the hierarchy?

• Classes also implement interfaces

– Interface is like a class with declarations but no code

• Classes may extend one other class, but can

implement many interfaces

– Multiple inheritance is tricky to understand/implement

7

Polymorphism in Java

• Subtyping is a kind of polymorphism

– Sometimes called subtype polymorphism

– Allows method to accept objects of many types

• Another kind: parametric polymorphism

– Implemented as generic methods in Java

• Ad-hoc polymorphism is overloading

– Method overloading

CMSC 433, Spring 2008 8

A Stack of Integers

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

9

Inner Classes

• Classes can be nested inside other classes

– These are called inner classes

• Within a class that contains an inner class, you

can use the inner class just like any other class

10

Referring to Outer Class

class Stack {

private int numEntries;

class Entry {

Integer elt; Entry next;

Entry(Integer i) { elt = i; next = null;

numEntries++; }

• Each inner “object” has an implicit reference to

the outer “object” whose method created it

– Can refer to fields directly, or use outer class name

13

IntegerStack Client

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

• This is OK, but what if we want other kinds of

stacks?

– Need to make one XStack for each kind of X

– Problems: Code bloat, maintainability nightmare

14

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; }}}

15

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

16

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

19

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

20

Parametric Polymorphism for Methods

• String is a subtype of Object

1. static Object id(Object x) { return x; }

2. static Object id(String x) { return x; }

3. static String id(Object x) { return x; }

4. static String id(String x) { return x; }

• Can’t pass an Object to 2 or 4

• 3 doesn’t type check

• Can pass a String to 1 but you get an Object back

21

Parametric Polymorphism, Again

• But id() doesn’t care about the type of x

– It works for any type

• So parameterize the static method :

static T id(T x) { return x; }

Integer j = id(new Integer(3));

– There’s no need to explicitly instantiate id; compiler

figures out the correct type.

  • In contrast, consider

List list = new ArrayList();

22

Standard Library, and Java 1.

• Part of Java 1.5 (called “generics”)

– Comes with replacement for java.util.*

  • class LinkedList { ...}
  • class HashMap { ... }
  • interface Collection { ... }

• But they didn’t change the JVM to add generics

– So how does that work?

– Will answer this question shortly.

25

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)

26

Solution I: Use Polymorphic Methods

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

used for anything

• Only works for methods, which can instantiate the type

differently at each call site.

– What should Class.forName(String) return?

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

27

Solution II: Wildcards

• Use? as the type variable

– Collection is “Collection of unknown”

• Why is this safe?

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

Legal Wildcard Usage

• Reasonable question:

  • Why is Stack not a subtype of Stack, but

Stack is a subtype of Stack? In both cases, I have

to cast the Stack’s elements to type Object.

• Answer:

  • Loosely speaking: wildcards permit reading but not writing.
  • In general, if a generic class C is declared as

class C { … }

  • When called on a C, methods that return T can have these

values cast to Object, but a method that takes T as an argument

can only be given null.

31

Bounded Wildcards

• We want drawAll to take a Collection of anything

that is a subtype of shape

– This is a bounded wildcard

– We can pass Collection

– We can safely treat s as a Shape

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

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 c) { c.add(new Circle()); }

33

Lower Bounded Wildcards (cont’d)

• But the following is allowed?

– Because c is a Collection of something that always

compatible with Circle

void foo(Collection c) { c.add(new Circle()); c.add(new Shape()); // fails } 34 **public interface Comparable { int compareTo(T o); } // e.g., Boolean implements Comparable public static > void sort(List list) { Object a[] = list.toArray(); Arrays.sort(a); ListIterator i = list.listIterator(); for(int j=0; j 37

Exercise: Annotate Java Libraries

• Look at the Java 1.4 API, and figure out how

you would best annotate the following classes

– Collection

– Comparator

– Collections

– Class

– Look at others too!

38

Translation via Erasure

• Replace uses of type variables with Object

– class A { ...T x;... } becomes

– class A { ...Object x;... }

• Add downcasts wherever necessary

– Integer x = A.get(); becomes

– Integer x = (Integer) (A.get());

• Uh...so why did we bother with generics if

they’re just going to be removed?

– Because the compiler still did type checking for us

– We know that those casts will not fail at run time

39

Limitations of Translation

• Some type information not available at run-time

  • Recall type variables T are rewritten to Object

• Thus, assuming T is a type variable

  • new T() would translate to new Object() (error)
  • new T[n] would translate to new Object[n] (warning)
  • Some casts/instanceofs that use T
    • (Only ones the compiler can figure out are allowed)

• Also produces some oddities

  • LinkedList.getClass() == LinkedList.getClass()
    • (These are uses of reflection to get the class object) 40

Using with Legacy Code

• Translation via type erasure

– class A becomes class A

• Thus class A is available as a “raw type”

– class A { ... }

– class B { A x; } // use A as raw type

• Sometimes useful with legacy code, but...

– Dangerous feature to use, plus unsafe

– Relies on implementation of generics, not semantics