Modulo I Java Generics

Size: px
Start display at page:

Download "Modulo I Java Generics"

Transcription

1 Modulo I Java Generics Prof. Ismael H F Santos April 05 Prof. Ismael H. F. Santos - ismael@tecgraf.puc-rio.br 1 Ementa Modulo I - Tópicos em JAVA Generics (incompleto!) April 05 Prof. Ismael H. F. Santos - ismael@tecgraf.puc-rio.br 2 1

2 Bibliografia Linguagem de Programação JAVA Ismael H. F. Santos, Apostila UniverCidade, 2002 The Java Tutorial: A practical guide for programmers Tutorial on-line: Java in a Nutshell David Flanagan, O Reilly & Associates Just Java 2 Mark C. Chan, Steven W. Griffith e Anthony F. Iasi, Makron Books. Java 1.2 Laura Lemay & Rogers Cadenhead, Editora Campos April 05 Prof. Ismael H. F. Santos - ismael@tecgraf.puc-rio.br 3 Livros Core Java 2, Cay S. Horstmann, Gary Cornell Volume 1 (Fundamentos) Volume 2 (Características Avançadas) Java: Como Programar, Deitel & Deitel Thinking in Patterns with JAVA, Bruce Eckel Gratuito. April 05 Prof. Ismael H. F. Santos - ismael@tecgraf.puc-rio.br 4 2

3 POO-Java Generics April 05 Prof. Ismael H. F. Santos - ismael@tecgraf.puc-rio.br 5 Concepts Generalizing Collection Classes Using Generics with other Java 1.5 Features Integration of Generics with Previous Releases User built generic classes April 05 Prof. Ismael H. F. Santos - ismael@tecgraf.puc-rio.br 6 3

4 What Are Generics? Generics abstract over Types Classes, Interfaces and Methods can be Parameterized by Types Generics provide increased readability and type safety April 05 Prof. Ismael H. F. Santos - ismael@tecgraf.puc-rio.br 7 Java Generic Programming Java has class Object Supertype of all object types This allows subtype polymorphism Can apply operation on class T to any subclass S <: T Java do not have templates No parametric polymorphism Many consider this the biggest deficiency of Java Java type system does not let you cheat Can cast from supertype to subtype Cast is checked at run time April 05 Prof. Ismael H. F. Santos - ismael@tecgraf.puc-rio.br 8 4

5 Generics (Cont d) A class definition with a type parameter is stored in a file and compiled just like any other class. Once a parameterized class is compiled, it can be used like any other class. However, the class type plugged in for the type parameter must be specified before it can be used in a program. Doing this is said to instantiate the generic class. Sample<String> object = new Sample<String>(); April 05 Prof. Ismael H. F. Santos - ismael@tecgraf.puc-rio.br 9 A Class Definition with a Type Parameter April 05 Prof. Ismael H. F. Santos - ismael@tecgraf.puc-rio.br 10 5

6 A Class Definition with a Type Parameter (Cont d) A class that is defined with a parameter for a type is called a generic class or a parameterized class The type parameter is included in angular brackets after the class name in the class definition heading. Any non-keyword identifier can be used for the type parameter, but by convention, the parameter starts with an uppercase letter. The type parameter can be used like other types used in the definition of a class. April 05 Prof. Ismael H. F. Santos - ismael@tecgraf.puc-rio.br 11 Tip: Compile with the -Xlint Option There are many pitfalls that can be encountered when using type parameters Compiling with the -Xlint option will provide more informative diagnostics of any problems or potential problems in the code javac Xlint Sample.java April 05 Prof. Ismael H. F. Santos - ismael@tecgraf.puc-rio.br 12 6

7 Example generic construct: Stack Stacks possible for any type of object For any type t, can have type stack_of_t Operations push, pop work for any type In C++, would write generic stack class template <type t> class Stack { private: t data; Stack<t> * next; public: void push (t* x) { t* pop ( ) { ; What can we do in Java? April 05 Prof. Ismael H. F. Santos - ismael@tecgraf.puc-rio.br 13 Simple Example Using Interfaces interface List<E> { void add(e x); Iterator<E> iterator(); interface Iterator<E> { E next(); boolean hasnext(); April 05 Prof. Ismael H. F. Santos - ismael@tecgraf.puc-rio.br 14 7

8 What Generics Are Not Generics are not templates Unlike C++, generic declarations are Typechecked at compile time Generics are compiled once and for all Generic source code not exposed to user No bloat The type checking with Java 1.5 Generics changes the way one programs (as the next few slides show) April 05 Prof. Ismael H. F. Santos - ismael@tecgraf.puc-rio.br 15 Java 1.0 vs Generics class Stack { void push(object o) {... Object pop() { String s = "Hello"; Stack st = new Stack();... st.push(s);... s = (String) st.pop(); class Stack<A> { void push(a a) {... A pop() { String s = "Hello"; Stack<String> st = new Stack<String>(); st.push(s);... s = st.pop(); April 05 Prof. Ismael H. F. Santos - ismael@tecgraf.puc-rio.br 16 8

9 Generic Class Definition: An Example April 05 Prof. Ismael H. F. Santos - ismael@tecgraf.puc-rio.br 17 Generic Class Definition: An Example (Cont d) April 05 Prof. Ismael H. F. Santos - ismael@tecgraf.puc-rio.br 18 9

10 Generic Class Usage: An Example April 05 Prof. Ismael H. F. Santos - ismael@tecgraf.puc-rio.br 19 Generic Class Usage: An Example (Cont d) Program Output: April 05 Prof. Ismael H. F. Santos - ismael@tecgraf.puc-rio.br 20 10

11 Java generics are type checked A generic class may use operations on objects of a parameter type Example: PriorityQueue<T> if x.less(y) then Two possible solutions C++: Link and see if all operations can be resolved Java: Type check and compile generics w/o linking This requires programmer to give information about type parameter Example: PriorityQueue<T extends...> April 05 Prof. Ismael H. F. Santos - ismael@tecgraf.puc-rio.br 21 How to Use Generics List<Integer> xs = new LinkedList<Integer>(); xs.add(new Integer(0)); Integer x = xs.iterator.next(); Compare with List xs = new LinkedList(); xs.add(new Integer(0)); Integer x = (Integer)xs.iterator.next(); April 05 Prof. Ismael H. F. Santos - ismael@tecgraf.puc-rio.br 22 11

12 A Generic Constructor Name Has No Type Parameter!!! Although the class name in a parameterized class definition has a type parameter attached, the type parameter is not used in the heading of the constructor definition: public Pair<T>() A constructor can use the type parameter as the type for a parameter of the constructor, but in this case, the angular brackets are not used: public Pair(T first, T second) However, when a generic class is instantiated, the angular brackets are used: Pair<String> pair= new Pair<STring>("Happy", "Day"); April 05 Prof. Ismael H. F. Santos - ismael@tecgraf.puc-rio.br 23 A Primitive Type Cannot be Plugged in for a Type Parameter!!! The type plugged in for a type parameter must always be a reference type: It cannot be a primitive type such as int, double, or char However, now that Java has automatic boxing, this is not a big restriction. Note: Reference types can include arrays. April 05 Prof. Ismael H. F. Santos - ismael@tecgraf.puc-rio.br 24 12

13 Limitations on Type Parameter Usage Within the definition of a parameterized class definition, there are places where an ordinary class name would be allowed, but a type parameter is not allowed. In particular, the type parameter cannot be used in simple expressions using new to create a new object For instance, the type parameter cannot be used as a constructor name or like a constructor: T object = new T(); T[] a = new T[10]; April 05 Prof. Ismael H. F. Santos - ismael@tecgraf.puc-rio.br 25 Limitations on Generic Class Instantiation Arrays such as the following are illegal: Pair<String>[] a = new Pair<String>[10]; Although this is a reasonable thing to want to do, it is not allowed given the way that Java implements generic classes April 05 Prof. Ismael H. F. Santos - ismael@tecgraf.puc-rio.br 26 13

14 Using Generic Classes and Automatic Boxing April 05 Prof. Ismael H. F. Santos - ismael@tecgraf.puc-rio.br 27 Using Generic Classes and Automatic Boxing (Cont d) Program Output: April 05 Prof. Ismael H. F. Santos - ismael@tecgraf.puc-rio.br 28 14

15 Collection Class Example HashMap<Intger, Double> hm = new HashMap<Intger, Double> (); // Note Auto-boxing from 15. hm.put (1,2.0); double coeff = hm.get(1); Hashmap 1.4 hm => Hashmap 1.5 <Object, Object> Hashmap 1.4 hm => Hashmap 1.5 <Object, Object> April 05 Prof. Ismael H. F. Santos - ismael@tecgraf.puc-rio.br 29 List Usage: Without Generics List ys = new LinkedList(); ys.add("zero"); List yss; yss = new LinkedList(); yss.add(ys); String y = (String) ((List)yss.iterator().next()).iterator().next(); // Evil run-time error time error Integer z = (Integer)ys.iterator().next(); April 05 Prof. Ismael H. F. Santos - ismael@tecgraf.puc-rio.br 30 15

16 List Usage: With Generics List<String> ys = new LinkedList<String>(); ys.add("zero"); List<List<String>> yss; yss = new LinkedList<List<String>>(); yss.add(ys); String y = yss.iterator().next().iterator().next(); // Compile-time error much better! Integer z = ys.iterator().next(); April 05 Prof. Ismael H. F. Santos - ismael@tecgraf.puc-rio.br 31 List Implementation w/o Generics class LinkedList implements List { protected class Node { Inner Inner Class Class Object elt; Remember these? these? Node next; Node(Object elt){elt = e; next = null; protected Node h, t; public LinkedList() {h = new Node(null); t = h; public void add(object elt){ t.next = new Node(elt); t = t.next; April 05 Prof. Ismael H. F. Santos - ismael@tecgraf.puc-rio.br 32 16

17 List Implementation With Generics class LinkedList<E >implements List<E> protected class Node { E elt; Node next; Node(E elt){elt = e; next = null; protected Node h, t; public LinkedList() {h = new Node(null); t = h; public void add(e elt){ t.next = new Node(elt); t = t.next; // April 05 Prof. Ismael H. F. Santos - ismael@tecgraf.puc-rio.br 33 Recall the Interator Interface class LinkedList<E >implements List<E> // public Iterator<E> iterator(){ example) example) return new Iterator<E>(){ protected Node p = h.next; public boolean hasnext(){return p!= null; public E next(){ E e = p.elt; p = p.next; return e; Anonymous Anonymous Inner Inner Class Class (see (see Swing Swing scribble scribble April 05 Prof. Ismael H. F. Santos - ismael@tecgraf.puc-rio.br 34 17

18 Multiple Type Parameters A generic class definition can have any number of type parameters. Multiple type parameters are listed in angular brackets just as in the single type parameter case, but are separated by commas. April 05 Prof. Ismael H. F. Santos - ismael@tecgraf.puc-rio.br 35 Multiple Type Parameters (Cont d) April 05 Prof. Ismael H. F. Santos - ismael@tecgraf.puc-rio.br 36 18

19 Multiple Type Parameters (Cont d) April 05 Prof. Ismael H. F. Santos - ismael@tecgraf.puc-rio.br 37 Using a Generic Class with Two Type Parameters Program Output: April 05 Prof. Ismael H. F. Santos - ismael@tecgraf.puc-rio.br 38 19

20 A Generic Classes and Exceptions It is not permitted to create a generic class with Exception, Error, Throwable, or any descendent class of Throwable A generic class cannot be created whose objects are throwable public class GEx<T> extends Exception The above example will generate a compiler error message April 05 Prof. Ismael H. F. Santos - ismael@tecgraf.puc-rio.br 39 Methods Can Be Generic Also interface Function<A,B>{ B value(a arg); interface Ntuple<T> { <S> Ntuple<S> map(function<t,s> f); Ntuple<Integer> nti =...; nti.map (new Function<Integer, Integer> { Integer value(integer i) { return new Integer(i.intValue()*2); ); April 05 Prof. Ismael H. F. Santos - ismael@tecgraf.puc-rio.br 40 20

21 Example: Generics and Inheritence 1 st consider this code w/o Generics class ListUtilities { public static Comparable max(list xs) { Iterator xi = xs.iterator(); Comparable w = (Comparable) xi.next(); while (xi.hasnext()) { Comparable x = (Comparable) xi.next(); if (w.compareto(x) < 0) w = x; return w; What dangers lurk lurk here? April 05 Prof. Ismael H. F. Santos - ismael@tecgraf.puc-rio.br 41 Consider what happens (and when) List xs = new LinkedList(); xs.add(new Byte(0)); Byte x = (Byte) ListUtilities.max(xs); List ys = new LinkedList(); ys.add(new Boolean(false)); // Evil run-time error Boolean y = (Boolean) ListUtilities.max(ys); April 05 Prof. Ismael H. F. Santos - ismael@tecgraf.puc-rio.br 42 21

22 With Generics We Get Compile Check List<Byte> xs = new LinkedList<Byte>(); xs.add(new Byte(0)); Byte x = ListUtilities.max(xs); List<Boolean> ys = new LinkedList<Boolean>(); ys.add(new Boolean(false)); // Compile-time error Boolean y = ListUtilities.max(ys); April 05 Prof. Ismael H. F. Santos - ismael@tecgraf.puc-rio.br 43 Generics and Inheritance Suppose you want to restrict the type parameter to express some restriction on the type parameter This can be done with a notion of subtypes Subtypes (weakly construed) can be expressed in Java using inheritance So it s a natural combination to combine inheritance with generics April 05 Prof. Ismael H. F. Santos - ismael@tecgraf.puc-rio.br 44 22

23 Priority Queue Example interface Comparable<I> { boolean lessthan(i); class PriorityQueue<T extends Comparable<T>> { T queue[ ] ; void insert(t t) {... if ( t.lessthan(queue[i]) )... T remove() { Said to be bounded Said to be bounded April 05 Prof. Ismael H. F. Santos - ismael@tecgraf.puc-rio.br 45 Bounded Parameterized Types The <E extends Number> syntax means that the type parameter of MathBox must be a subclass of the Number class We say that the type parameter is bounded new MathBox<Integer>(5); //Legal new MathBox<Double>(32.1); //Legal new MathBox<String>( No good! );//Illegal April 05 Prof. Ismael H. F. Santos - ismael@tecgraf.puc-rio.br 46 23

24 Bounded Parameterized Types Inside a parameterized class, the type parameter serves as a valid type. So the following is valid. public class OuterClass<T> { private class InnerClass<E extends T> { Syntax note: The <A extends B> syntax is valid even if B is an interface. April 05 Prof. Ismael H. F. Santos - ismael@tecgraf.puc-rio.br 47 Bounded Parameterized Types Java allows multiple inheritance in the form of implementing multiple interfaces, so multiple bounds may be necessary to specify a type parameter. The following syntax is used then: <T extends A & B & C & > Example interface A { interface B { class MultiBounds<T extends A & B> { April 05 Prof. Ismael H. F. Santos - ismael@tecgraf.puc-rio.br 48 24

25 Using a Generic Class with Two Type Parameters Program Output: April 05 Prof. Ismael H. F. Santos - ismael@tecgraf.puc-rio.br 49 Bounds for Type Parameters Sometimes it makes sense to restrict the possible types that can be plugged in for a type parameter T. For instance, to ensure that only classes that implement the Comparable interface are plugged in for T, define a class as follows: public class RClass<T extends Comparable> "extends Comparable" serves as a bound on the type parameter T. Any attempt to plug in a type for T which does not implement the Comparable interface will result in a compiler error message. April 05 Prof. Ismael H. F. Santos - ismael@tecgraf.puc-rio.br 50 25

26 Bounds for Type Parameters (Cont d) A bound on a type may be a class name (rather than an interface name) Then only descendent classes of the bounding class may be plugged in for the type parameters: public class ExClass<T extends Class1> A bounds expression may contain multiple interfaces and up to one class. If there is more than one type parameter, the syntax is as follows: public class Two<T1 extends Class1, T2 extends Class2 & Comparable> April 05 Prof. Ismael H. F. Santos - ismael@tecgraf.puc-rio.br 51 Bounds for Type Parameters (Cont d) April 05 Prof. Ismael H. F. Santos - ismael@tecgraf.puc-rio.br 52 26

27 Another example interface LessAndEqual<I> { boolean lessthan(i); boolean equal(i); class Relations<C extends LessAndEqual<C>> extends C { boolean greaterthan(relations<c> a) { return a.lessthan(this); boolean greaterequal(relations<c> a) { return greaterthan(a) equal(a); boolean notequal(relations<c> a) {... boolean lessequal(relations<c> a) { April 05 Prof. Ismael H. F. Santos - ismael@tecgraf.puc-rio.br 53 Generics and Subtyping Is the following code snippet legal? List<String> ls = new ArrayList<String>(); //1 List<Object> lo = ls; //2 Line 1 is certainly legal. What about line 2? Is a List of Strings a List of Object. Intuitive answer for most is sure!. But wait! The following code (if line 2 were allowed) would attempt to assign an Object to a String! For For all all types P and and C (i.e (i.ec is is a subtype subtype of of P) P) lo.add(new Object()); // 3 Subtype(P,C)!=>!=> String s = ls.get(0); // 4: Subtype(Generic<P>,Generic<C>) April 05 Prof. Ismael H. F. Santos - ismael@tecgraf.puc-rio.br 54 27

28 Subclassing a generic class import java.awt.color; public class Subclass extends MyClass<Color> { // You almost always need to supply a constructor public Subclass(Color color) { super(color); public static void main(string[ ] args) { Subclass sc = new Subclass(Color.GREEN); sc.print(color.white); April 05 Prof. Ismael H. F. Santos - ismael@tecgraf.puc-rio.br 55 Generic Interfaces An interface can have one or more type parameters. The details and notation are the same as they are for classes with type parameters. April 05 Prof. Ismael H. F. Santos - ismael@tecgraf.puc-rio.br 56 28

29 Generic Methods When a generic class is defined, the type parameter can be used in the definitions of the methods for that generic class. In addition, a generic method can be defined that has its own type parameter that is not the type parameter of any class A generic method can be a member of an ordinary class or a member of a generic class that has some other type parameter. The type parameter of a generic method is local to that method, not to the class. April 05 Prof. Ismael H. F. Santos - ismael@tecgraf.puc-rio.br 57 Generic Methods (Cont d) The type parameter must be placed (in angular brackets) after all the modifiers, and before the returned type: public static <T> T genmethod(t[] a) When one of these generic methods is invoked, the method name is prefaced with the type to be plugged in, enclosed in angular brackets String s = NonG.<String>genMethod(c); April 05 Prof. Ismael H. F. Santos - ismael@tecgraf.puc-rio.br 58 29

30 Inheritance with Generic Classes A generic class can be defined as a derived class of an ordinary class or of another generic class As in ordinary classes, an object of the subclass type would also be of the superclass type Given two classes: A and B, and given G: a generic class, there is no relationship between G<A> and G<B> This is true regardless of the relationship between class A and B, e.g., if class B is a subclass of class A April 05 Prof. Ismael H. F. Santos - ismael@tecgraf.puc-rio.br 59 A Derived Generic Class: An Example April 05 Prof. Ismael H. F. Santos - ismael@tecgraf.puc-rio.br 60 30

31 A Derived Generic Class: An Example (Cont d) Program Output: April 05 Prof. Ismael H. F. Santos - ismael@tecgraf.puc-rio.br 61 Wildcards Consider the problem of writing code that prints out all the elements in a collection before 1.5. void printcollection(collection c) { Iterator i = c.iterator(); for (k = 0; k < c.size(); k++) { System.out.println(i.next()); April 05 Prof. Ismael H. F. Santos - ismael@tecgraf.puc-rio.br 62 31

32 1 st Naïve Try w/ Generics void printcollection(collection<object> c) { for (Object e : c) { System.out.println(e); The problem is that this new version is much less useful than the old one. The old code could be called with any kind of collection as a parameter, The new code only takes Collection<Object>, which, as is not a supertypeof all kinds of collections! April 05 Prof. Ismael H. F. Santos - ismael@tecgraf.puc-rio.br 63 Correct way Use Wildcards So what is the supertype of all kinds of collections? Pronounced collection of unknown and denoted Collection<?>, A collection whose element type matches anything. It s called a wildcard type for obvious reasons. void printcollection(collection<?> c) { for (Object e : c) { System.out.println(e); April 05 Prof. Ismael H. F. Santos - ismael@tecgraf.puc-rio.br 64 32

33 Using Wildcards Again public class Census { public static void addregistry(map<string,? extends Person> registry) { // Assuming Drivers are a subtype of Person Map<String, Driver> alldrivers =...; Census.addRegistry(allDrivers); April 05 Prof. Ismael H. F. Santos - ismael@tecgraf.puc-rio.br 65 Implementing Generics Type erasure Compile-time type checking uses generics Compiler eliminates generics by erasing them Compile List<T> to List, T to Object, insert casts Generics are not templates Generic declarations are typechecked Generics are compiled once and for all No instantiation No code bloat April 05 Prof. Ismael H. F. Santos - ismael@tecgraf.puc-rio.br 66 33

34 How Do Generics Affect My Code? They don t except for the way you ll code! Non-generic code can use generic libraries; For example, existing code will run unchanged with generic Collection library April 05 Prof. Ismael H. F. Santos - ismael@tecgraf.puc-rio.br 67 Erasure Erasure erases all generics type argument information at compilation phase. E.g. List<String> is converted to List E.g. String t = stringlist.iterator().next() is converted to String t = (String) stringlist.iterator().next() As part of its translation, a compiler will map every parameterized type to its type erasure. April 05 Prof. Ismael H. F. Santos - ismael@tecgraf.puc-rio.br 68 34

35 Erasure List <String> l1 = new ArrayList<String>(); List<Integer> l2 = new ArrayList<Integer>(); System.out.println(l1.getClass() == l2.getclass()); April 05 Prof. Ismael H. F. Santos - ismael@tecgraf.puc-rio.br 69 35

Generalizing Collection Classes Using Generics with other Java 1.5 Features Integration of Generics with Previous Releases User built generic classes

Generalizing Collection Classes Using Generics with other Java 1.5 Features Integration of Generics with Previous Releases User built generic classes Java Generics 1 Concepts Generalizing Collection Classes Using Generics with other Java 1.5 Features Integration of Generics with Previous Releases User built generic classes 2 What Are Generics? Generics

More information

Introduction to Generics. Defining a Class with a Type Parameter

Introduction to Generics. Defining a Class with a Type Parameter Introduction to Generics Beginning with version 5.0, Java allows class and method definitions that include parameters for types Such definitions are called generics Generic programming with a type parameter

More information

Copyright 2007 Pearson Addison-Wesley Copyright 2018 Aiman Hanna All rights reserved

Copyright 2007 Pearson Addison-Wesley Copyright 2018 Aiman Hanna All rights reserved Comp 249 Programming Methodology Chapter 13 Generics & The ArrayList Class Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia University, Montreal, Canada These slides has

More information

Generalized Code. Fall 2011 (Honors) 2

Generalized Code. Fall 2011 (Honors) 2 CMSC 202H Generics Generalized Code One goal of OOP is to provide the ability to write reusable, generalized code. Polymorphic code using base classes is general, but restricted to a single class hierarchy

More information

Generic programming in OO Languages

Generic programming in OO Languages CS 242 2012 Generic programming in OO Languages Reading Text: Sections 9.4.1 and 9.4.3 J Koskinen, Metaprogramming in C++, Sections 2 5 Gilad Bracha, Generics in the Java Programming Language Questions

More information

1.1. Annotations History Lesson - C/C++

1.1. Annotations History Lesson - C/C++ 1. Additions Thanks to Dr. James Heliotis. He started it all :) See also here: and see also here: and here: You need to use the tools from the Java release candidate 1 % bash % export PATH=/usr/local/j2sdk1.5.0-rc1/bin:$PATH

More information

Generics עזאם מרעי המחלקה למדעי המחשב אוניברסיטת בן-גוריון

Generics עזאם מרעי המחלקה למדעי המחשב אוניברסיטת בן-גוריון Generics עזאם מרעי המחלקה למדעי המחשב אוניברסיטת בן-גוריון 2 Example List myintlist = new LinkedList(); // 1 myintlist.add(new Integer(0)); // 2 Integer x = (Integer) myintlist.iterator().next(); // 3

More information

JAVA V Source files Java, winter semester

JAVA V Source files Java, winter semester JAVA Source files 17.10.2017 1 Unicode programs ~ Unicode comments, identifiers, char and string constants the rest is in ASCII (

More information

JAVA V Assertions Java, winter semester

JAVA V Assertions Java, winter semester JAVA Assertions 1 Assertion since Java 1.4 the statement with a boolean expression a developer supposes that the expression is always satisfied (evaluates to true) if it is evaluated to false -> error

More information

Generics, Type Safety, and Dynamic Data Structures

Generics, Type Safety, and Dynamic Data Structures Generics, Type Safety, and Dynamic Data Structures 1 Reminders No classes, labs, recitations next week (gobble gobble) Consulting hours Monday only Project 8 (the final one!) is out start early Milestone

More information

Generics עזאם מרעי המחלקה למדעי המחשב אוניברסיטת בן-גוריון

Generics עזאם מרעי המחלקה למדעי המחשב אוניברסיטת בן-גוריון Generics עזאם מרעי המחלקה למדעי המחשב אוניברסיטת בן-גוריון 2 Example List myintlist = new LinkedList(); // 1 myintlist.add(new Integer(0)); // 2 Integer x = myintlist.iterator().next(); // 3 3 Example

More information

Generics in Java and Beyond

Generics in Java and Beyond Generics in Java and Beyond Martin Buechi 2001 by Martin Büchi 1 Overview Generics Abstraction of generic concepts. C++ templates (STL), parameterized types, ML polymorphic data types and functions, Beta

More information

CMSC 202. Generics II

CMSC 202. Generics II CMSC 202 Generics II Generic Sorting We can now implement sorting functions that can be used for any class (that implements Comparable). The familiar insertion sort is shown below.!! public static

More information

Software Engineering. Prof. Agostino Poggi

Software Engineering. Prof. Agostino Poggi Agent and Object Technology Lab Dipartimento di Ingegneria dell Informazione Università degli Studi di Parma Software Engineering Generics Prof. Agostino Poggi public class ListOfIntegers { //... fields...

More information

Java Generics Java, summer semester

Java Generics Java, summer semester Java Generics Introduction similar to the templates in C#/C++ but only on first view typed arguments goal clear code type safety Motivational example without generics (

More information

CS108, Stanford Handout #8. Java Generics

CS108, Stanford Handout #8. Java Generics CS108, Stanford Handout #8 Fall, 2007-08 Nick Parlante Java Generics Java generics (added in version 5) are a mixed bag. Some uses of generics are simple to understand and make the code cleaner. They are

More information

11/7/18 JAVA GENERICS. Java Collections. Java Collections. Using Java Collections. Proposals for adding Generics to Java.

11/7/18 JAVA GENERICS. Java Collections. Java Collections. Using Java Collections. Proposals for adding Generics to Java. JAVA GENERICS Lecture CS110 Fall 018 Photo credit: Andrew Kennedy Java Collections Early versions of Java lacked generics interface Collection { /** Return true iff the collection contains ob */ boolean

More information

6. Generic and Virtual Types

6. Generic and Virtual Types 6. Generic and Virtual Types For many programming scenarios, subtype polymorphism is not the best choice. Often more precise type systems are desirable: Types with parameters Specialization of used types

More information

Subtyping for behaviour?

Subtyping for behaviour? Subtyping for behaviour? 10/26/10 1 Subtyping for behaviour the inner style class Reservation { date... ; customer... ; void print() { // print Date and Customer inner; class FlightReservation extends

More information

Problems. Java Generics. Example. Example. Often you need the same behavior for different kind of classes

Problems. Java Generics. Example. Example. Often you need the same behavior for different kind of classes Problems Often you need the same behavior for different kind of classes Java Generics Use Object references to accommodate any object type Use Generic classes and Method The use of Object references induces

More information

Outline. 1 Generic Classes. 2 Generics and Subtyping. Generics. Guy Wiener. Generic Classes. Generics and Subtyping

Outline. 1 Generic Classes. 2 Generics and Subtyping. Generics. Guy Wiener. Generic Classes. Generics and Subtyping Outline 1 2 Outline 1 2 (Parametric) classes are classes that have Parameters A generic class with a concrete type parameter is an instance of the generic class The type parameter can be the type of variables,

More information

Lecture Outline. Parametric Polymorphism and Java Generics. Polymorphism. Polymorphism

Lecture Outline. Parametric Polymorphism and Java Generics. Polymorphism. Polymorphism Lecture Outline Parametric Polymorphism and Java Generics Parametric polymorphism Java generics Declaring and instantiating generics Bounded types: restricting instantiations Generics and subtyping. Wildcards

More information

6. Parametric Types and Virtual Types

6. Parametric Types and Virtual Types 6. Parametric Types and Virtual Types For many programming scenarios, subtype polymorphism is not the best choice. Often more precise type systems are desirable: Types with parameters Specialization of

More information

Photo credit: Andrew Kennedy JAVA GENERICS

Photo credit: Andrew Kennedy JAVA GENERICS Photo credit: Andrew Kennedy JAVA GENERICS Lecture 17 CS2110 Spring 2017 Java Collections 2 Early versions of Java lacked generics interface Collection { /** Return true iff the collection contains ob

More information

COURSE 4 PROGRAMMING III OOP. JAVA LANGUAGE

COURSE 4 PROGRAMMING III OOP. JAVA LANGUAGE COURSE 4 PROGRAMMING III OOP. JAVA LANGUAGE PREVIOUS COURSE CONTENT Inheritance Abstract classes Interfaces instanceof operator Nested classes Enumerations COUSE CONTENT Collections List Map Set Aggregate

More information

Java Generics -- an introduction. Based on https://docs.oracle.com/javase/tutorial/java/generics/why.html

Java Generics -- an introduction. Based on https://docs.oracle.com/javase/tutorial/java/generics/why.html Java Generics -- an introduction Based on https://docs.oracle.com/javase/tutorial/java/generics/why.html Generics vs. Templates Templates in C++ are compiled into unique code based on the types passed

More information

The collections interfaces

The collections interfaces Generics in Java Advanced Programming 4/18/16 1 The collections interfaces Contains unique elements Maps unique keys to values 4/18/16 2 Collections in Java Array has a special language support Iterators

More information

#Students per correct answers

#Students per correct answers Generics in Java Programming Projects 14/04/15 1 #Students per correct answers Quiz"2" 10" 9" 8" 7" 6" 5" 4" 3" 2" 1" 0" 10" 9" 8" 7" 6" 5" 4" 3" 2" 1" 0" #"Correct"Answers" 10" 9" 8" 7" 6" 5" 4" 3" 2"

More information

Polymorphism. CMSC 330: Organization of Programming Languages. Two Kinds of Polymorphism. Polymorphism Overview. Polymorphism

Polymorphism. CMSC 330: Organization of Programming Languages. Two Kinds of Polymorphism. Polymorphism Overview. Polymorphism CMSC 330: Organization of Programming Languages Polymorphism Polymorphism Definition Feature that allows values of different data types to be handled using a uniform interface Applicable to Functions Ø

More information

Subtyping for behaviour?

Subtyping for behaviour? Subtyping for behaviour? Reservation date customer print() FlightReservation flight seat print() TrainReservation train waggon seat print() 10/23/2009 1 Subtyping for behaviour the inner style class Reservation

More information

The list abstract data type defined a number of operations that all list-like objects ought to implement:

The list abstract data type defined a number of operations that all list-like objects ought to implement: Chapter 7 Polymorphism Previously, we developed two data structures that implemented the list abstract data type: linked lists and array lists. However, these implementations were unsatisfying along two

More information

PARAMETRIC POLYMORPHISM

PARAMETRIC POLYMORPHISM PARAMETRIC POLYMORPHISM Java C#! Parametric polymorphism: " Java Generics and Generic C# for.net! The idea: the compiler is able to check parametric classes just looking at their definilon 1 Java Generics

More information

CSE 331. Generics (Parametric Polymorphism)

CSE 331. Generics (Parametric Polymorphism) CSE 331 Generics (Parametric Polymorphism) slides created by Marty Stepp based on materials by M. Ernst, S. Reges, D. Notkin, R. Mercer, Wikipedia http://www.cs.washington.edu/331/ 1 Parametric polymorphism

More information

CSE 331 Software Design and Implementation. Lecture 14 Generics 2

CSE 331 Software Design and Implementation. Lecture 14 Generics 2 CSE 331 Software Design and Implementation Lecture 14 Generics 2 James Wilcox / Winter 2016 Hi, I m James! Big picture Last time: Generics intro Subtyping and Generics Using bounds for more flexible subtyping

More information

CSE 143 Lecture 26. Advanced collection classes. (ADTs; abstract classes; inner classes; generics; iterators) read 11.1, 9.6, ,

CSE 143 Lecture 26. Advanced collection classes. (ADTs; abstract classes; inner classes; generics; iterators) read 11.1, 9.6, , CSE 143 Lecture 26 Advanced collection classes (ADTs; abstract classes; inner classes; generics; iterators) read 11.1, 9.6, 15.3-15.4, 16.4-16.5 slides created by Marty Stepp, adapted by Alyssa Harding

More information

C# Adds Useful Features

C# Adds Useful Features C# Adds Useful Features Events and delegates are included to handle asynchronous actions (like keyboard or mouse actions). Properties allow user-defined read and write actions for fields. You can add get

More information

Polymorphic (Generic) Programming in Java

Polymorphic (Generic) Programming in Java Polymorphic (Generic) Programming in Java We have used the fact that Java classes are arranged as a tree with the built in class Object at the root to write generic or polymorphic code such as the following

More information

CSCE 314 Programming Languages

CSCE 314 Programming Languages CSCE 314 Programming Languages! Java Generics II Dr. Hyunyoung Lee!!! 1 Type System and Variance Within the type system of a programming language, variance refers to how subtyping between complex types

More information

CSE 331 Software Design and Implementation. Lecture 14 Generics 2

CSE 331 Software Design and Implementation. Lecture 14 Generics 2 CSE 331 Software Design and Implementation Lecture 14 Generics 2 Zach Tatlock / Spring 2018 Big picture Last time: Generics intro Subtyping and Generics Using bounds for more flexible subtyping Using wildcards

More information

Parametric polymorphism and Generics

Parametric polymorphism and Generics Parametric polymorphism and Generics Today s Lecture Outline Parametric polymorphism Java generics Declaring and instantiating generics Bounded types: restricting instantiations Generics and subtyping.

More information

Subtyping for behaviour?

Subtyping for behaviour? Subtyping for behaviour? Reservation date customer FlightReservation flight seat print() print() TrainReservation train waggon seat print() 10/4/2004 1 Subtyping for behaviour BETA style class Reservation

More information

Announcements. Java Graphics. Exceptions. Java Odds & Ends

Announcements. Java Graphics. Exceptions. Java Odds & Ends Java Odds & Ends Lecture 25 CS211 Fall 2005 Final Exam Wednesday, 12/14 9:00-11:30am Uris Aud Review Session Sunday, 12/11 1:00-2:30pm Kimball B11 Check your final exam schedule! Announcements For exam

More information

CS61B Lecture #25: Java Generics. Last modified: Thu Oct 18 21:04: CS61B: Lecture #25 1

CS61B Lecture #25: Java Generics. Last modified: Thu Oct 18 21:04: CS61B: Lecture #25 1 CS61B Lecture #25: Java Generics Last modified: Thu Oct 18 21:04:53 2018 CS61B: Lecture #25 1 The Old Days Java library types such as List didn t used to be parameterized. All Lists were lists of Objects.

More information

1 Shyam sir JAVA Notes

1 Shyam sir JAVA Notes 1 Shyam sir JAVA Notes 1. What is the most important feature of Java? Java is a platform independent language. 2. What do you mean by platform independence? Platform independence means that we can write

More information

Introduction to Programming Using Java (98-388)

Introduction to Programming Using Java (98-388) Introduction to Programming Using Java (98-388) Understand Java fundamentals Describe the use of main in a Java application Signature of main, why it is static; how to consume an instance of your own class;

More information

CSE Lecture 7: Polymorphism and generics 16 September Nate Nystrom UTA

CSE Lecture 7: Polymorphism and generics 16 September Nate Nystrom UTA CSE 3302 Lecture 7: Polymorphism and generics 16 September 2010 Nate Nystrom UTA 2 Polymorphism poly = many morph = shape Allow a variable to contain values with different types 3 Subtype polymorphism

More information

CS61B Lecture #25: Java Generics. Last modified: Thu Oct 19 19:36: CS61B: Lecture #25 1

CS61B Lecture #25: Java Generics. Last modified: Thu Oct 19 19:36: CS61B: Lecture #25 1 CS61B Lecture #25: Java Generics Last modified: Thu Oct 19 19:36:29 2017 CS61B: Lecture #25 1 The Old Days Java library types such as List didn t used to be parameterized. All Lists were lists of Objects.

More information

CSE 331 Software Design and Implementation. Lecture 13 Generics 1

CSE 331 Software Design and Implementation. Lecture 13 Generics 1 CSE 331 Software Design and Implementation Lecture 13 Generics 1 Zach Tatlock / Spring 2018 Varieties of abstraction Abstraction over computation: procedures (methods) int x1, y1, x2, y2; Math.sqrt(x1*x1

More information

Rules and syntax for inheritance. The boring stuff

Rules and syntax for inheritance. The boring stuff Rules and syntax for inheritance The boring stuff The compiler adds a call to super() Unless you explicitly call the constructor of the superclass, using super(), the compiler will add such a call for

More information

Exercise 8 Parametric polymorphism November 18, 2016

Exercise 8 Parametric polymorphism November 18, 2016 Concepts of Object-Oriented Programming AS 2016 Exercise 8 Parametric polymorphism November 18, 2016 Task 1 Consider the following Scala classes: class A class B extends A class P1[+T] class P2[T

More information

CSE 331 Software Design & Implementation

CSE 331 Software Design & Implementation CSE 331 Software Design & Implementation Hal Perkins Autumn 2013 Generics (Polymorphism) (Slides by Mike Ernst and David Notkin) 1 Varieties of abstraction Abstraction over computation: procedures int

More information

3. Subtyping and Parametric Types

3. Subtyping and Parametric Types 3. Subtyping and Parametric Types Overview: Typing of objects Subtype polymorphism A Generic type system Virtual types Motivation: Basic notions of type systems Typing as very light-weight specification

More information

Announcements. Lecture 15 Generics 2. Announcements. Big picture. CSE 331 Software Design and Implementation

Announcements. Lecture 15 Generics 2. Announcements. Big picture. CSE 331 Software Design and Implementation CSE 331 Software Design and Implementation Lecture 15 Generics 2 Announcements Leah Perlmutter / Summer 2018 Announcements Quiz 5 is due tomorrow Homework 6 due tomorrow Section tomorrow! Subtyping now

More information

CSE 331 Software Design and Implementation. Lecture 15 Generics 2

CSE 331 Software Design and Implementation. Lecture 15 Generics 2 CSE 331 Software Design and Implementation Lecture 15 Generics 2 Leah Perlmutter / Summer 2018 Announcements Announcements Quiz 5 is due tomorrow Homework 6 due tomorrow Section tomorrow! Subtyping now

More information

Generics. IRS W-9 Form

Generics. IRS W-9 Form Generics IRS W-9 Form Generics Generic class and methods. BNF notation Syntax Non-parametrized class: < class declaration > ::= "class" < identifier > ["extends" < type >] ["implements" < type list >]

More information

+ Abstract Data Types

+ Abstract Data Types Linked Lists Abstract Data Types An Abstract Data Type (ADT) is: a set of values a set of operations Sounds familiar, right? I gave a similar definition for a data structure. Abstract Data Types Abstract

More information

Java Review: Objects

Java Review: Objects Outline Java review Abstract Data Types (ADTs) Interfaces Class Hierarchy, Abstract Classes, Inheritance Invariants Lists ArrayList LinkedList runtime analysis Iterators Java references 1 Exam Preparation

More information

Comp215: Thinking Generically

Comp215: Thinking Generically Comp215: Thinking Generically Dan S. Wallach (Rice University) Copyright 2015, Dan S. Wallach. All rights reserved. Functional APIs On Wednesday, we built a list of Objects. This works. But it sucks. class

More information

School of Computer Science CPS109 Course Notes 5 Alexander Ferworn Updated Fall 15

School of Computer Science CPS109 Course Notes 5 Alexander Ferworn Updated Fall 15 Table of Contents 1 INTRODUCTION... 1 2 IF... 1 2.1 BOOLEAN EXPRESSIONS... 3 2.2 BLOCKS... 3 2.3 IF-ELSE... 4 2.4 NESTING... 5 3 SWITCH (SOMETIMES KNOWN AS CASE )... 6 3.1 A BIT ABOUT BREAK... 7 4 CONDITIONAL

More information

CMSC 341. Nilanjan Banerjee

CMSC 341. Nilanjan Banerjee CMSC 341 Nilanjan Banerjee http://www.csee.umbc.edu/~nilanb/teaching/341/ Announcements Just when you thought Shawn was going to teach this course! On a serious note: register on Piazza I like my classes

More information

Collections and Iterators. Collections

Collections and Iterators. Collections Collections and Iterators Based on the notes from David Fernandez-Baca and Steve Kautz Based on The Java Tutorial (http://docs.oracle.com/javase/tutorial/java/) Bryn Mawr College CS206 Intro to Data Structures

More information

Java: exceptions and genericity

Java: exceptions and genericity Chair of Software Engineering Carlo A. Furia, Marco Piccioni, Bertrand Meyer Java: exceptions and genericity Chair of Software Engineering Carlo A. Furia, Marco Piccioni, Bertrand Meyer Exceptions Exceptions

More information

Primitive Types. Four integer types: Two floating-point types: One character type: One boolean type: byte short int (most common) long

Primitive Types. Four integer types: Two floating-point types: One character type: One boolean type: byte short int (most common) long Primitive Types Four integer types: byte short int (most common) long Two floating-point types: float double (most common) One character type: char One boolean type: boolean 1 2 Primitive Types, cont.

More information

CS 231 Data Structures and Algorithms, Fall 2016

CS 231 Data Structures and Algorithms, Fall 2016 CS 231 Data Structures and Algorithms, Fall 2016 Dr. Bruce A. Maxwell Department of Computer Science Colby College Course Description Focuses on the common structures used to store data and the standard

More information

CMSC 202H. Containers and Iterators

CMSC 202H. Containers and Iterators CMSC 202H Containers and Iterators Container Definition A container is a data structure whose purpose is to hold objects. Most languages support several ways to hold objects Arrays are compiler-supported

More information

09/02/2013 TYPE CHECKING AND CASTING. Lecture 5 CS2110 Spring 2013

09/02/2013 TYPE CHECKING AND CASTING. Lecture 5 CS2110 Spring 2013 1 TYPE CHECKING AND CASTING Lecture 5 CS2110 Spring 2013 1 Type Checking 2 Java compiler checks to see if your code is legal Today: Explore how this works What is Java doing? Why What will Java do if it

More information

Generics method and class definitions which involve type parameters.

Generics method and class definitions which involve type parameters. Contents Topic 07 - Generic Programming I. Introduction Example 1 User defined Generic Method: printtwice(t x) Example 2 User defined Generic Class: Pair Example 3 using java.util.arraylist II. Type

More information

Java Fundamentals (II)

Java Fundamentals (II) Chair of Software Engineering Languages in Depth Series: Java Programming Prof. Dr. Bertrand Meyer Java Fundamentals (II) Marco Piccioni static imports Introduced in 5.0 Imported static members of a class

More information

Java Bytecode (binary file)

Java Bytecode (binary file) Java is Compiled Unlike Python, which is an interpreted langauge, Java code is compiled. In Java, a compiler reads in a Java source file (the code that we write), and it translates that code into bytecode.

More information

C# Generics. Object Oriented Programming (236703) Winter

C# Generics. Object Oriented Programming (236703) Winter C# Generics Object Oriented Programming (236703) Winter 2014-5 C# Generics in a nutshell Outline Generics what is it good for? C# generics semantics Generics and reflection Limitations Variance 2 Why Do

More information

Advanced Programming - JAVA Lecture 4 OOP Concepts in JAVA PART II

Advanced Programming - JAVA Lecture 4 OOP Concepts in JAVA PART II Advanced Programming - JAVA Lecture 4 OOP Concepts in JAVA PART II Mahmoud El-Gayyar elgayyar@ci.suez.edu.eg Ad hoc-polymorphism Outline Method overloading Sub-type Polymorphism Method overriding Dynamic

More information

generic programming alberto ferrari university of parma

generic programming alberto ferrari university of parma generic programming alberto ferrari university of parma contents generic programming java generic programming methods & generic programming classes & generic programming java with generics generic methods

More information

CS61B Lecture #24. Today: Java support for generic programming. Readings for today: A Java Reference, Chapter 10.

CS61B Lecture #24. Today: Java support for generic programming. Readings for today: A Java Reference, Chapter 10. CS61B Lecture #24 Today: Java support for generic programming Readings for today: A Java Reference, Chapter 10. Readings for Monday: Data Structures, 6.4. Last modified: Fri Oct 19 19:33:03 2012 CS61B:

More information

Fall 2017 CISC124 9/16/2017

Fall 2017 CISC124 9/16/2017 CISC124 Labs start this week in JEFF 155: Meet your TA. Check out the course web site, if you have not already done so. Watch lecture videos if you need to review anything we have already done. Problems

More information

Collections, Maps and Generics

Collections, Maps and Generics Collections API Collections, Maps and Generics You've already used ArrayList for exercises from the previous semester, but ArrayList is just one part of much larger Collections API that Java provides.

More information

Discussion. Type 08/12/2016. Language and Type. Type Checking Subtypes Type and Polymorphism Inheritance and Polymorphism

Discussion. Type 08/12/2016. Language and Type. Type Checking Subtypes Type and Polymorphism Inheritance and Polymorphism Type Joseph Spring Discussion Languages and Type Type Checking Subtypes Type and Inheritance and 7COM1023 Programming Paradigms 1 2 Type Type denotes the kind of values that programs can manipulate: Simple

More information

Java Object Oriented Design. CSC207 Fall 2014

Java Object Oriented Design. CSC207 Fall 2014 Java Object Oriented Design CSC207 Fall 2014 Design Problem Design an application where the user can draw different shapes Lines Circles Rectangles Just high level design, don t write any detailed code

More information

Announcements. Lecture 14 Generics 1. Announcements. CSE 331 Software Design and Implementation. Leah Perlmutter / Summer 2018

Announcements. Lecture 14 Generics 1. Announcements. CSE 331 Software Design and Implementation. Leah Perlmutter / Summer 2018 CSE 331 Software Design and Implementation Lecture 14 Generics 1 Announcements Leah Perlmutter / Summer 2018 Announcements Quiz 5 is due Thursday Homework 6 due Thursday Midterm grades and feedback will

More information

CSE 331 Software Design and Implementation. Lecture 14 Generics 1

CSE 331 Software Design and Implementation. Lecture 14 Generics 1 CSE 331 Software Design and Implementation Lecture 14 Generics 1 Leah Perlmutter / Summer 2018 Announcements Announcements Quiz 5 is due Thursday Homework 6 due Thursday Midterm grades and feedback will

More information

Nested Classes in Java. Slides by: Alon Mishne Edited by: Eran Gilad, Eyal Moscovici April 2013

Nested Classes in Java. Slides by: Alon Mishne Edited by: Eran Gilad, Eyal Moscovici April 2013 Nested Classes in Java Slides by: Alon Mishne Edited by: Eran Gilad, Eyal Moscovici April 2013 1 In This Tutorial Explanation of the nested class concept. Access modifiers and nested classes. The types

More information

Declarations and Access Control SCJP tips

Declarations and Access Control  SCJP tips Declarations and Access Control www.techfaq360.com SCJP tips Write code that declares, constructs, and initializes arrays of any base type using any of the permitted forms both for declaration and for

More information

Introduction To Java. Chapter 1. Origins of the Java Language. Origins of the Java Language. Objects and Methods. Origins of the Java Language

Introduction To Java. Chapter 1. Origins of the Java Language. Origins of the Java Language. Objects and Methods. Origins of the Java Language Chapter 1 Getting Started Introduction To Java Most people are familiar with Java as a language for Internet applications We will study Java as a general purpose programming language The syntax of expressions

More information

Classes, subclasses, subtyping

Classes, subclasses, subtyping 1 CSCE 314: Programming Languages Dr. Flemming Andersen Classes, subclasses, subtyping 2 3 Let me try to explain to you, what to my taste is characteristic for all intelligent thinking. It is, that one

More information

Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub

Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub Lebanese University Faculty of Science Computer Science BS Degree Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub 2 Crash Course in JAVA Classes A Java

More information

The ArrayList class CSC 123 Fall 2018 Howard Rosenthal

The ArrayList class CSC 123 Fall 2018 Howard Rosenthal The ArrayList class CSC 123 Fall 2018 Howard Rosenthal Lesson Goals Describe the ArrayList class Discuss important methods of this class Describe how it can be used in modeling Much of the information

More information

CMSC 132: Object-Oriented Programming II

CMSC 132: Object-Oriented Programming II CMSC 132: Object-Oriented Programming II Object-Oriented Programming Intro Department of Computer Science University of Maryland, College Park Object-Oriented Programming (OOP) Approach to improving software

More information

Properties of an identifier (and the object it represents) may be set at

Properties of an identifier (and the object it represents) may be set at Properties of an identifier (and the object it represents) may be set at Compile-time These are static properties as they do not change during execution. Examples include the type of a variable, the value

More information

CIS 120 Final Exam 15 December 2017

CIS 120 Final Exam 15 December 2017 CIS 120 Final Exam 15 December 2017 Name (printed): Pennkey (login id): My signature below certifies that I have complied with the University of Pennsylvania s Code of Academic Integrity in completing

More information

Generic types. Announcements. Raw ArrayLists. Generic types (cont.) Creating a raw ArrayList: Accessing a raw ArrayList:

Generic types. Announcements. Raw ArrayLists. Generic types (cont.) Creating a raw ArrayList: Accessing a raw ArrayList: Announcements PS 3 is ready Midterm exam 1: Tuesday, April 11, in class Closed book but one sheet, both sides, of A4 paper is allowed Today s topic: Generics (parameterized types) Readings for this slide

More information

Closed book but one sheet, both sides, of A4 paper is allowed. Section 2.5 of the text Generics in the Java Programming Languages by Gilad Bracha

Closed book but one sheet, both sides, of A4 paper is allowed. Section 2.5 of the text Generics in the Java Programming Languages by Gilad Bracha Announcements PS 3 is ready Midterm exam 1: Tuesday, April 11, in class Closed book but one sheet, both sides, of A4 paper is allowed Today s topic: Generics (parameterized types) Readings for this slide

More information

Principles of Software Construction: Objects, Design and Concurrency. Mutability and Java Potpourri. toad Fall 2013

Principles of Software Construction: Objects, Design and Concurrency. Mutability and Java Potpourri. toad Fall 2013 Principles of Software Construction: Objects, Design and Concurrency Mutability and Java Potpourri 15-214 toad Fall 2013 Jonathan Aldrich Charlie Garrod School of Computer Science 2012-13 C Garrod, J Aldrich,

More information

Administrivia. Java Review. Objects and Variables. Demo. Example. Example: Assignments

Administrivia. Java Review. Objects and Variables. Demo. Example. Example: Assignments CMSC433, Spring 2004 Programming Language Technology and Paradigms Java Review Jeff Foster Feburary 3, 2004 Administrivia Reading: Liskov, ch 4, optional Eckel, ch 8, 9 Project 1 posted Part 2 was revised

More information

CSCI 135 Exam #2 Fundamentals of Computer Science I Fall 2013

CSCI 135 Exam #2 Fundamentals of Computer Science I Fall 2013 CSCI 135 Exam #2 Fundamentals of Computer Science I Fall 2013 Name: This exam consists of 6 problems on the following 6 pages. You may use your two-sided hand-written 8 ½ x 11 note sheet during the exam.

More information

Introduction to Visual Basic and Visual C++ Introduction to Java. JDK Editions. Overview. Lesson 13. Overview

Introduction to Visual Basic and Visual C++ Introduction to Java. JDK Editions. Overview. Lesson 13. Overview Introduction to Visual Basic and Visual C++ Introduction to Java Lesson 13 Overview I154-1-A A @ Peter Lo 2010 1 I154-1-A A @ Peter Lo 2010 2 Overview JDK Editions Before you can write and run the simple

More information

Chapter 13 Object Oriented Programming. Copyright 2006 The McGraw-Hill Companies, Inc.

Chapter 13 Object Oriented Programming. Copyright 2006 The McGraw-Hill Companies, Inc. Chapter 13 Object Oriented Programming Contents 13.1 Prelude: Abstract Data Types 13.2 The Object Model 13.4 Java 13.1 Prelude: Abstract Data Types Imperative programming paradigm Algorithms + Data Structures

More information

LaboratoriodiProgrammazione III

LaboratoriodiProgrammazione III LaboratoriodiProgrammazione III Lezione 15: Portabilità e Sicurezza, Java Massimo Tivoli Origins of the language James Gosling and others at Sun, 1990 95 Oak language for set top box small networked device

More information

IC Language Specification

IC Language Specification CS 301 Spring 2016 IC Language Specification The IC Language For the implementation project, you will build a compiler for an object-oriented language called IC (for Irish Coffee 1 ), which is essentially

More information

Java How to Program, 10/e. Copyright by Pearson Education, Inc. All Rights Reserved.

Java How to Program, 10/e. Copyright by Pearson Education, Inc. All Rights Reserved. Java How to Program, 10/e Education, Inc. All Rights Reserved. Each class you create becomes a new type that can be used to declare variables and create objects. You can declare new classes as needed;

More information

Harvard School of Engineering and Applied Sciences Computer Science 152

Harvard School of Engineering and Applied Sciences Computer Science 152 Harvard School of Engineering and Applied Sciences Computer Science 152 Lecture 17 Tuesday, March 30, 2010 1 Polymorph means many forms. Polymorphism is the ability of code to be used on values of different

More information

Inner Classes. CMSC 433 Programming Language Technologies and Paradigms Spring Example: The Queue Class. Example: The Queue Class (cont d)

Inner Classes. CMSC 433 Programming Language Technologies and Paradigms Spring Example: The Queue Class. Example: The Queue Class (cont d) CMSC 433 Programming Language Technologies and Paradigms Spring 2007 Inner Classes & Iterators Mar. 6, 2007 Inner Classes Classes can be nested inside other classes These are called inner classes Within

More information