Top Banner
Compilation 2007 Compilation 2007 Java 1.5 Features Java 1.5 Features Michael I. Schwartzbach BRICS, University of Aarhus
29

Compilation 2007 Java 1.5 Features Michael I. Schwartzbach BRICS, University of Aarhus.

Dec 21, 2015

Download

Documents

Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Compilation 2007 Java 1.5 Features Michael I. Schwartzbach BRICS, University of Aarhus.

Compilation 2007Compilation 2007

Java 1.5 FeaturesJava 1.5 Features

Michael I. Schwartzbach

BRICS, University of Aarhus

Page 2: Compilation 2007 Java 1.5 Features Michael I. Schwartzbach BRICS, University of Aarhus.

2Java 1.5 Features

Java 1.5 Features (That We Will Use)Java 1.5 Features (That We Will Use)

enums autoboxing improved for loop generic collections generic classes @override annotations covariant return types

Page 3: Compilation 2007 Java 1.5 Features Michael I. Schwartzbach BRICS, University of Aarhus.

3Java 1.5 Features

Constant Values as Static Fields (1/2)Constant Values as Static Fields (1/2)

public class Test {

public static final int TrafficSignal_RED = 0;

public static final int TrafficSignal_YELLOW = 1;

public static final int TrafficSignal_GREEN = 2;

public static int duration(int color) {

switch (color) {

case TrafficSignal_RED: return 35;

case TrafficSignal_YELLOW: return 15;

case TrafficSignal_GREEN: return 40;

}

return 0;

}

public static String name(int color) {

switch (color) {

case TrafficSignal_RED: return "RED";

case TrafficSignal_YELLOW: return "YELLOW";

case TrafficSignal_GREEN: return "GREEN";

}

return "";

}

Page 4: Compilation 2007 Java 1.5 Features Michael I. Schwartzbach BRICS, University of Aarhus.

4Java 1.5 Features

Constant Values as Static Fields (2/2)Constant Values as Static Fields (2/2)

public static void main(String[] args) throws Exception {

int[] states = { TrafficSignal_RED, TrafficSignal_YELLOW,

TrafficSignal_GREEN, TrafficSignal_YELLOW };

int i = 0;

while (true) {

System.out.println(name(states[i]));

Thread.sleep(1000*duration(states[i]));

i = (i+1)%states.length;

}

}

}

• Not typesafe

• No proper namespace

• Constants compiled into clients

• Annoying to use

Page 5: Compilation 2007 Java 1.5 Features Michael I. Schwartzbach BRICS, University of Aarhus.

5Java 1.5 Features

Type-Safe EnumsType-Safe Enums

public class Test {

public enum TrafficSignal { RED, YELLOW, GREEN };

public static int duration(TrafficSignal color) {

switch (color) {

case RED: return 35;

case YELLOW: return 15;

case GREEN: return 40;

}

return 0;

}

public static void main(String[] args) throws Exception {

TrafficSignal[] states = { TrafficSignal.RED, TrafficSignal.YELLOW,

TrafficSignal.GREEN, TrafficSignal.YELLOW };

int i = 0;

while (true) {

System.out.println(states[i]);

Thread.sleep(1000*duration(states[i]));

i = (i+1)%states.length;

}

}

}

Page 6: Compilation 2007 Java 1.5 Features Michael I. Schwartzbach BRICS, University of Aarhus.

6Java 1.5 Features

Constructors, Fields, and MethodsConstructors, Fields, and Methods

public class Test {

public enum TrafficSignal {

RED(35), YELLOW(15), GREEN(40);

protected int duration;

TrafficSignal(int duration) { this.duration = duration; }

int getDuration() { return duration; }

};

public static void main(String[] args) throws Exception {

TrafficSignal[] states = { TrafficSignal.RED,

TrafficSignal.YELLOW,

TrafficSignal.GREEN,

TrafficSignal.YELLOW };

int i = 0;

while (true) {

System.out.println(states[i]);

Thread.sleep(1000*states[i].getDuration());

i = (i+1)%states.length;

}

}

}

Page 7: Compilation 2007 Java 1.5 Features Michael I. Schwartzbach BRICS, University of Aarhus.

7Java 1.5 Features

int i1 = 42;

Integer i2;

i2 = new Integer(i1);

i1 = i2.intValue();

Map m = new HashMap();

m.put(new Integer(87), new Integer(i1));

i2 = (Integer)m.get(new Integer(87));

Annoying ConversionsAnnoying Conversions

Page 8: Compilation 2007 Java 1.5 Features Michael I. Schwartzbach BRICS, University of Aarhus.

8Java 1.5 Features

int i1 = 42;

Integer i2;

i2 = new Integer(i1);

i1 = i2.intValue();

Map m = new HashMap();

m.put(new Integer(87), new Integer(i1));

i2 = (Integer)m.get(new Integer(87)); int i1 = 42;

int i1 = 42;

Integer i2;

i2 = i1;

i1 = i2;

Map m = new HashMap();

m.put(87, i1);

i2 = (Integer)m.get(87);

Automatic Boxing and UnboxingAutomatic Boxing and Unboxing

Page 9: Compilation 2007 Java 1.5 Features Michael I. Schwartzbach BRICS, University of Aarhus.

9Java 1.5 Features

Getting Rid of the Last CastGetting Rid of the Last Cast

int i1 = 42;

Integer i2;

i2 = i1;

i1 = i2;

Map m = new HashMap();

m.put(87, i1);

i2 = (Integer)m.get(87);

int i1 = 42;

Integer i2;

i2 = i1;

i1 = i2;

Map<Integer,Integer> m = new HashMap<Integer,Integer>();

m.put(87, i1);

i2 = m.get(87);

Page 10: Compilation 2007 Java 1.5 Features Michael I. Schwartzbach BRICS, University of Aarhus.

10Java 1.5 Features

Generic CollectionsGeneric Collections

Type parameters Type checker inserts the required casts The type checker ensures casts will never fail The type checker warns if it is not sure No runtime improvement, casts still take place

(unless JVM optimizes) Required to be backward compatible

Page 11: Compilation 2007 Java 1.5 Features Michael I. Schwartzbach BRICS, University of Aarhus.

11Java 1.5 Features

Generic Collections in ActionGeneric Collections in Action

Student johnni = new Student(”Johnni");

List<Student> phds = new ArrayList<Student>();

phds.add(johnni);

Student phd = phds.get(0); // no cast needed

phds.add(”Janus"); // cool type error

for (Iterator<Student> i = phds.iterator();

i.hasNext(); ) {

Student p = i.next(); // no cast needed

System.out.println(p.name());

if (p.papers() < 3) i.remove();

}

Page 12: Compilation 2007 Java 1.5 Features Michael I. Schwartzbach BRICS, University of Aarhus.

12Java 1.5 Features

No Type Information at RuntimeNo Type Information at Runtime

List<Student> phds = new ArrayList<Student>();

phds instanceof List // true

phds instanceof List<Student> // syntax error

Page 13: Compilation 2007 Java 1.5 Features Michael I. Schwartzbach BRICS, University of Aarhus.

13Java 1.5 Features

Mixing Raw and Generic CollectionsMixing Raw and Generic Collections

Student johnni = new Student(“Johnni");

List phds = new ArrayList();

phds.add(johnni);

phds.add(“Janus"); // no type error

for (Iterator<Student> i = phds.iterator(); i.hasNext(); ) {

Student p = i.next(); // no cast needed

System.out.println(p.name());

if (p.papers() < 3) i.remove();

}

Compiles, but fails at runtime. But the compiler warns you:

Note: Test.java uses unchecked or unsafe operations.

Note: Recompile with -Xlint:unchecked for details.

Page 14: Compilation 2007 Java 1.5 Features Michael I. Schwartzbach BRICS, University of Aarhus.

14Java 1.5 Features

Nesting Parameterized TypesNesting Parameterized Types

Map<Advisor, List<Student>> phdSchool;

Map<String,Map<Advisor, List<Student>>> phdSchools;

Advisor michael;

...

System.out.println(

phdSchools.get("BRICS").get(michael).get(0).name()

);

Page 15: Compilation 2007 Java 1.5 Features Michael I. Schwartzbach BRICS, University of Aarhus.

15Java 1.5 Features

Invariant Subtyping of ParametersInvariant Subtyping of Parameters

class Student extends Person { ... }

...

List<Person> people = new ArrayList<Person>();

// perfectly fine since ArrayList is a subtype of List

List<Student> phds = new ArrayList<Student>();

// perfectly fine since ArrayList is a subtype of List

people = phds; // type error

Page 16: Compilation 2007 Java 1.5 Features Michael I. Schwartzbach BRICS, University of Aarhus.

16Java 1.5 Features

And for a Good ReasonAnd for a Good Reason

class Student extends Person { ... }

class Advisor extends Person { ... }

...

List<Person> people = new ArrayList<Person>();

List<Student> phds new ArrayList<Student>();

people = phds; // assume this is allowed

people.add(new Advisor("Michael"));

phds.get(0).studentid();

// runtime error, an Advisor doesn't have a studentid

Page 17: Compilation 2007 Java 1.5 Features Michael I. Schwartzbach BRICS, University of Aarhus.

17Java 1.5 Features

Same Problem with ArraysSame Problem with Arrays

class Student extends Person { ... }

class Advisor extends Person { ... }

...

Student[] phds = new Student[100];

Person[] people = new Person[100];

people = phds; // allowed, but unsound

people[0] = new Advisor();

phds[0].studentid(); // runtime error

Pragmatic (but later regretted) design choice

Page 18: Compilation 2007 Java 1.5 Features Michael I. Schwartzbach BRICS, University of Aarhus.

18Java 1.5 Features

Print All Elements of Any ListPrint All Elements of Any List

public void printList(List x) throws IOException {

for (Iterator i = x.iterator(); i.hasNext(); ) {

System.out.println(i.next().toString());

}

}

List<Student> phds;

List<Person> people;

printList(phds); // unchecked warning

printList(people); // unchecked warning

Page 19: Compilation 2007 Java 1.5 Features Michael I. Schwartzbach BRICS, University of Aarhus.

19Java 1.5 Features

Another Attempt with GenericsAnother Attempt with Generics

public void printList(List<Object> x)

throws IOException {

for (Iterator<Object> i = x.iterator();

i.hasNext(); ) {

System.out.println(i.next().toString());

}

}

List<Student> phds;

List<Person> people;

printList(phds); // type error

printList(people); // type error

Page 20: Compilation 2007 Java 1.5 Features Michael I. Schwartzbach BRICS, University of Aarhus.

20Java 1.5 Features

Wildcards to The RescueWildcards to The Rescue

public void printList(List<?> x) throws IOException {

for (Iterator<?> i = x.iterator(); i.hasNext(); ) {

System.out.println(i.next().toString());

}

}

List<Student> phds;

List<Person> people;

printList(phds); // allowed

printList(people); // allowed

Page 21: Compilation 2007 Java 1.5 Features Michael I. Schwartzbach BRICS, University of Aarhus.

21Java 1.5 Features

Write Your Own Generic ClassWrite Your Own Generic Class

public class Queue<T> {

protected List<T> s;

public Queue() {

s = new ArrayList<T>();

}

public void enter(T x) {

s.add(x);

}

public T leave() {

if (s.size()==0) return null;

else return s.remove(0);

}

}

Page 22: Compilation 2007 Java 1.5 Features Michael I. Schwartzbach BRICS, University of Aarhus.

22Java 1.5 Features

Bounded Type ParametersBounded Type Parameters

class PersonQueue<T extends Person> {

protected List<T> s;

public PersonQueue() {

s = new ArrayList<T>();

}

public void enter(T x) {

s.add(x);

}

public T leave() {

if (s.size()==0) return null;

else return s.remove(0);

}

public String first() {

if (s.size()==0) return null;

return s.get(0).name();

}

}

Page 23: Compilation 2007 Java 1.5 Features Michael I. Schwartzbach BRICS, University of Aarhus.

23Java 1.5 Features

Using InheritanceUsing Inheritance

class PersonQueue<T extends Person> extends Queue<T> {

public String first() {

return s.get(0).name();

}

}

Page 24: Compilation 2007 Java 1.5 Features Michael I. Schwartzbach BRICS, University of Aarhus.

24Java 1.5 Features

For Loop for Collection ClassesFor Loop for Collection Classes

for (Iterator<Person> i = phds.iterator(); i.hasNext(); ) {

Person p = i.next();

System.out.println(p.name());

}

for (Person p: phds) {

System.out.println(p.name());

}

But we cannot remove, need old iterators for that

Page 25: Compilation 2007 Java 1.5 Features Michael I. Schwartzbach BRICS, University of Aarhus.

25Java 1.5 Features

Person phds[] = { new Person(”Johnni"),

new Person(”Janus") };

for (Person p: phds) {

System.out.println(p.name());

}

Works for Arrays as WellWorks for Arrays as Well

Page 26: Compilation 2007 Java 1.5 Features Michael I. Schwartzbach BRICS, University of Aarhus.

26Java 1.5 Features

Override ProblemOverride Problem

public class Graduate extends Person {

public String naem() {

return super.name()+", PhD";

}

}

Nothing happens, the PhD disappeared

Page 27: Compilation 2007 Java 1.5 Features Michael I. Schwartzbach BRICS, University of Aarhus.

27Java 1.5 Features

The The @Override@Override Annotation Annotation

public class Graduate extends Person {

public @Override String naem() {

return super.name()+", PhD";

}

}

Compiler error:

method does not override a method from its superclass

Page 28: Compilation 2007 Java 1.5 Features Michael I. Schwartzbach BRICS, University of Aarhus.

28Java 1.5 Features

Return Type ProblemReturn Type Problem

public class Person {

protected String name;

public Person(String name) {

this.name = name;

}

public Person changeName(String newName) {

this.name = newName;

return this;

}

}

...

public Student extends Person { ... }

...

Student x;

...

x.changeName(”Johnny").papers() // type error

Page 29: Compilation 2007 Java 1.5 Features Michael I. Schwartzbach BRICS, University of Aarhus.

29Java 1.5 Features

Covariant Return TypesCovariant Return Types

public Student extends Person {

public Student changeName(String newName) {

this.name = newName;

return this;

}

...

}

x.changeName(“Johnny").papers() // allowed