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

Slides:



Advertisements
Similar presentations
New features in JDK 1.5 Can these new and complex features simplify Java development?
Advertisements

Java Review Interface, Casting, Generics, Iterator.
1-May-15 Java 1.5. Reason for changes “The new language features all have one thing in common: they take some common idiom and provide linguistic support.
CHAPTER 12 GENERICS Introduction to java 1. Assignment 5 Solution See Eclipse.
Generic programming in Java
1 CISC370: Inheritance James Atlas. June 17, 2008James Atlas - CISC3702 Questions? Assignment 1 Assignment 1 Review Review.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 21 Generics.
Java Generics.
Lecture 27 Exam outline Boxing of primitive types in Java 1.5 Generic types in Java 1.5.
11-Jun-15 Generics. A generic is a method that is recompiled with different types as the need arises The bad news: Instead of saying: List words = new.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved L13 (Chapter 21) Generics.
Java Generics. 2 The Dark Ages: Before Java 5 Java relied only on inclusion polymorphism  A polymorphism code = Using a common superclass Every class.
Generics OOP Tirgul What is it good for ? Stack myStack = new Stack() ; // old version (1.4.2) myStack.push(new Integer(0)) ; int x = ((Integer)
Creating Generic Classes. Introduction Java Generics were added to allow for type- safe collections and eliminate the need for burdensome, code-cluttering.
1 Generics and Using a Collection Generics / Parameterized Classes Using a Collection Customizing a Collection using Inheritance Inner Classes Use of Exceptions.
J2SE 5.0 New Features. J2SE 5.0 aka JDK 1.5 aka Tiger.
Java Review Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
30-Jun-15 Generics. Arrays and collections In Java, array elements must all be of the same type: int[] counts = new int[10]; String[] names = { "Tom",
1 Chapter 21 Generics. 2 Objectives F To know the benefits of generics (§21.1). F To use generic classes and interfaces (§21.2). F To declare generic.
Generic Subroutines and Exceptions CS351 – Programming Paradigms.
15-Jul-15 Generics. ArrayList s and arrays A ArrayList is like an array of Object s, but... Arrays use [ ] syntax; ArrayList s use object syntax An ArrayList.
Generic Java 21/ What is generics? To be able to assign type variables to a class These variables are not bound to any specific type until the.
Chapter 21 Generics 1. Generics - Overview Generic Methods specify a set of related methods Generic classes specify a set of related types Software reuse.
Effective Java: Generics Last Updated: Spring 2009.
CSC 243 – Java Programming, Spring 2013 March 12, 2013 Week 7, Generics.
Generics1 Parametrized classes and methods. Generics2 What are generics Generics are classes or interfaces that can be instantiated with a variety of.
Generics1 Parametrized classes and methods. Generics2 What are generics Generics are classes or interfaces that can be instantiated with a variety of.
Generics1 Parametrized classes and methods. Generics2 What are generics Generics are classes or interfaces that can be instantiated with a variety of.
ArrayList, Multidimensional Arrays
Generics CSCI 201L Jeffrey Miller, Ph.D. HTTP :// WWW - SCF. USC. EDU /~ CSCI 201 USC CSCI 201L.
Core Java: Essential Features 08/05/2015 Kien Tran.
Java 5 Part 1 CSE301 University of Sunderland Harry Erwin, PhD.
Java Generics Compiled from Core Java Technologies Tech Tips By Billy B. L. Lim.
CompSci 100E 40.1 Java 5 New Features  Generics  Enhanced for loop  Autoboxing/unboxing  Typesafe enums  Other  Varargs  Static Import  Metadata.
G ENERICS I N J AVA BY: Ankit Goyal Sankalp Singh.
Generics CompSci 230 S Software Construction.
CSE 143 Lecture 24 Advanced collection classes (ADTs; abstract classes; inner classes; generics; iterators) read 11.1, 9.6, , slides.
Types in programming languages1 What are types, and why do we need them?
Objects First With Java A Practical Introduction Using BlueJ Supplementary Material for Java
Introduction to Generics
Java 5 Part 2 CSE301 University of Sunderland Harry Erwin, PhD.
CMSC 330: Organization of Programming Languages Java Generics.
Generic Data Structures "Get your data structures correct first, and the rest of the program will write itself." - David Jones EE 422CGenerics 1.
Georgia Institute of Technology What is new in Java 5.0 (1.5)? Barb Ericson Georgia Institute of Technology June 2006.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 19 Generics.
Parametric Polymorphism and Java Generics. Announcements One day extension on HW5 Because of an error in my HW5 config HW6 out, due November 10 Grades.
Java Type System and Object Model Horstmann ch , 7.7.
GENERICS AND THE JAVA COLLECTIONS FRAMEWORK Lecture 16 CS2110 – Fall 2015 Photo credit: Andrew Kennedy.
SOEN 343 Software Design Section H Fall 2006 Dr Greg Butler
Recitation 5 Enums and The Java Collections classes/interfaces 1.
More Java: Static and Final, Abstract Class and Interface, Exceptions, Collections Framework 1 CS300.
1 CSC 2053 New from AutoBoxing 3 Before J2SE 5.0, working with primitive types required the repetitive work of converting between the primitive.
Bart van Kuik Application Developer Oracle Corporation.
COMP Inheritance and Polymorphism Yi Hong June 09, 2015.
1 Chapter 21 Generics. 2 Objectives F To use generic classes and interfaces (§21.2). F To declare generic classes and interfaces (§21.3). F To understand.
James Wilcox / Winter 2016 CSE 331 Software Design and Implementation Lecture 14 Generics 2.
CSC 520 – Advanced Object Oriented Programming, Fall, 2010 Thursday, September 30 Week 5, Generics and Inheritance Techniques, Meyer Ch. 10 & 16.
Comp1004: Environments The Java Library. Coming up Recap – Encapsulation – Constructors – Loops – Arrays – ArrayList – Iterators The Java Library – Implementation.
New Java Features Advanced Programming Techniques.
Sixth Lecture ArrayList Abstract Class and Interface
CIS265/506 Cleveland State University – Prof. Victor Matos
More on Java Generics Multiple Generic Types Bounded Generic Types
Introducing Java Generics and Collections
Generics A Brief Review 16-Nov-18.
Java Programming Language
Generics 27-Nov-18.
Generic programming in Java
Effective Java: 3rd Edition Generics
Java 5 New Features 1-May-19.
Generics 2-May-19.
Presentation transcript:

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

2 Java 1.5 Features Java 1.5 Features (That We Will Use)  enums  autoboxing  improved for loop  generic collections  generic classes annotations  covariant return types

3 Java 1.5 Features 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 ""; }

4 Java 1.5 Features 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

5 Java 1.5 Features Type-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; }

6 Java 1.5 Features Constructors, 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; }

7 Java 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 Conversions

8 Java 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 Unboxing

9 Java 1.5 Features Getting 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 m = new HashMap (); m.put(87, i1); i2 = m.get(87);

10 Java 1.5 Features Generic 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

11 Java 1.5 Features Generic Collections in Action Student johnni = new Student(”Johnni"); List phds = new ArrayList (); phds.add(johnni); Student phd = phds.get(0); // no cast needed phds.add(”Janus"); // cool type error for (Iterator i = phds.iterator(); i.hasNext(); ) { Student p = i.next(); // no cast needed System.out.println(p.name()); if (p.papers() < 3) i.remove(); }

12 Java 1.5 Features No Type Information at Runtime List phds = new ArrayList (); phds instanceof List // true phds instanceof List // syntax error

13 Java 1.5 Features Mixing Raw and Generic Collections Student johnni = new Student(“Johnni"); List phds = new ArrayList(); phds.add(johnni); phds.add(“Janus"); // no type error for (Iterator 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.

14 Java 1.5 Features Nesting Parameterized Types Map > phdSchool; Map >> phdSchools; Advisor michael;... System.out.println( phdSchools.get("BRICS").get(michael).get(0).name() );

15 Java 1.5 Features Invariant Subtyping of Parameters class Student extends Person {... }... List people = new ArrayList (); // perfectly fine since ArrayList is a subtype of List List phds = new ArrayList (); // perfectly fine since ArrayList is a subtype of List people = phds; // type error

16 Java 1.5 Features And for a Good Reason class Student extends Person {... } class Advisor extends Person {... }... List people = new ArrayList (); List phds new ArrayList (); people = phds; // assume this is allowed people.add(new Advisor("Michael")); phds.get(0).studentid(); // runtime error, an Advisor doesn't have a studentid

17 Java 1.5 Features Same 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

18 Java 1.5 Features Print 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 phds; List people; printList(phds); // unchecked warning printList(people); // unchecked warning

19 Java 1.5 Features Another Attempt with Generics public void printList(List x) throws IOException { for (Iterator i = x.iterator(); i.hasNext(); ) { System.out.println(i.next().toString()); } List phds; List people; printList(phds); // type error printList(people); // type error

20 Java 1.5 Features Wildcards to The Rescue public void printList(List x) throws IOException { for (Iterator i = x.iterator(); i.hasNext(); ) { System.out.println(i.next().toString()); } List phds; List people; printList(phds); // allowed printList(people); // allowed

21 Java 1.5 Features Write Your Own Generic Class public class Queue { protected List s; public Queue() { s = new ArrayList (); } public void enter(T x) { s.add(x); } public T leave() { if (s.size()==0) return null; else return s.remove(0); }

22 Java 1.5 Features Bounded Type Parameters class PersonQueue { protected List s; public PersonQueue() { s = new ArrayList (); } 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(); }

23 Java 1.5 Features Using Inheritance class PersonQueue extends Queue { public String first() { return s.get(0).name(); }

24 Java 1.5 Features For Loop for Collection Classes for (Iterator 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

25 Java 1.5 Features Person phds[] = { new Person(”Johnni"), new Person(”Janus") }; for (Person p: phds) { System.out.println(p.name()); } Works for Arrays as Well

26 Java 1.5 Features Override Problem public class Graduate extends Person { public String naem() { return super.name()+", PhD"; }  Nothing happens, the PhD disappeared

27 Java 1.5 Features Annotation public class Graduate extends Person { String naem() { return super.name()+", PhD"; }  Compiler error: method does not override a method from its superclass

28 Java 1.5 Features Return 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

29 Java 1.5 Features Covariant Return Types public Student extends Person { public Student changeName(String newName) { this.name = newName; return this; }... } x.changeName(“Johnny").papers() // allowed