Java Brand Generics. Advanced Topics in Java. Khalid Azim Mughal Version date:

Size: px
Start display at page:

Download "Java Brand Generics. Advanced Topics in Java. Khalid Azim Mughal Version date:"

Transcription

1 Java Brand Generics Advanced Topics in Java Khalid Azim Mughal Version date: Khalid Azim Mughal Java Brand Generics 1/40 Overview Introduction to Generics Basic Java Generics Increasing Expressive Power with Wildcard Type Parameters Generic Interfaces Generic Methods Translation by Type Erasure Other Implications and Restrictions regarding Java Generics Further Study and Resources Khalid Azim Mughal Java Brand Generics 2/40

2 INTRODUCTION TO GENERICS The Role of Generics in Programming Languages Java Brand of Generics Khalid Azim Mughal Java Brand Generics 3/40 The Role of Generics in Programming Languages Generics 1 allow definition and implementation of generic abstractions. The generic type is parameterized by one or more formal type parameters. The actual type parameters are supplied when the generic type is instantiated. A parameterized type thus represents a set of types depending on the actual type parameters supplied. Recurring theme in the evolution of programming languages For example: Ada, Clu, C++, C#, Eiffel, and now Java "One List to Rule Them All!" 1. a.k.a. Genericity, Parametric polymorphism Khalid Azim Mughal Java Brand Generics 4/40

3 Java Brand of Generics Goal: Provide extra type information at compile time to avoid verbosity and the necessity of explicit type checking and casting at runtime. Compile-time Java Generics (JG): Reference types (classes, interfaces and array types) and methods can be parameterized with type information. Generics implemented as compiler transformations, with insignificant impact on the JVM. Benefits: Increased language expressiveness with improved type safety Khalid Azim Mughal Java Brand Generics 5/40 BASIC JAVA GENERICS The Need for Generics Generic Types Parameterized Types Canonical usage with Collections Khalid Azim Mughal Java Brand Generics 6/40

4 Canonical Problem: Collections w/o Generics A collection without generics can hold references to objects of any type. List wordlist = new ArrayList(); // Using a generic reference for the list. wordlist.add("two zero zero five"); // Can add any object. wordlist.add(new Integer(2004)); //... Object element = wordlist.get(0); //... if (element instanceof String) { // Runtime check to avoid ClassCastException String strint = (String) element;// Cast required. //... Inheritance allows the implementation of the class to be specific, but its use to be generic. An ArrayList is a specific implementation of the List interface, usage of the class ArrayList is generic with regard to any object. Khalid Azim Mughal Java Brand Generics 7/40 Using parameterized types: Collections w/ Generics List<String> wordlist = new ArrayList<String>(); // Using a specific type. wordlist.add(c); // Can add only strings wordlist.add(new Integer(2004)); // Compile-time error! //... String element = wordlist.get(0); // Only strings as elements //... No runtime check or explicit cast necessary! Generic types allow the implementation of class to be generic, but its use to be specific. The generic type ArrayList<E> is a generic implementation of the List<E> interface, usage of the parameterized type ArrayList<String> is specific, as it constrains the generic type ArrayList<E> to strings. // Implementation in the java.util package public interface List<E> extends Collection<E> {... public class ArrayList<E> extends AbstractList<E> {... Khalid Azim Mughal Java Brand Generics 8/40

5 Generic Types and Parameterized Types A generic type is a reference type that defines a set of formal type parameters or type variables (E 1, E 2...E n ) that must be provided for its invocation. public class ArrayList<E> extends AbstractList<E> {... // (1) Declaration The (formal) type parameter is an unqualified identifier. The type parameter E can be used (pretty much) as any other type in the class, although a type parameter cannot be used to create a new instance. A generic type without its formal type parameters is called a raw type. ArrayList is the raw type of the generic type ArrayList<E>. An invocation or instantiation (usually called a parameterized type) is a specific usage of a generic type where the formal type parameters are replaced by actual type parameters. ArrayList<String> mylist = new ArrayList<String>(); // (2) Invocation Methods can be called on objects of generic types, no extra syntax is required: mylist.add("two zero zero five"); We can declare references of generic types, instantiate generic classes, and call methods on the objects. Khalid Azim Mughal Java Brand Generics 9/40 General Remarks on Java Generics The compiler ensures that the parameterized type is used correctly so that errors are caught at compile time, and not at runtime. Generics are implemented in the compiler; no generic type info is available at runtime. A parameterized type does not create a new class. The invocations share the generic type. Invocation of generic types is restricted to reference types (excluding array creation and enumerations), and primitive types are not permitted as type parameters. Khalid Azim Mughal Java Brand Generics 10/40

6 Example of legacy code: LegacySeq Any object can be maintained in a sequence, the client must do the bookkeeping. public class LegacySeq { private Object element; // Data private LegacySeq tail; // Rest of the sequence LegacySeq(Object element, LegacySeq tail) { this.element = element; this.tail = tail; public void setelement(object obj) { element = obj; public Object getelement() { return element; public void settail(legacyseq tail) { this.tail = tail; public LegacySeq gettail() { return this.tail; //... // Client code LegacySeq intseq = new LegacySeq(32, new LegacySeq(16, null)); intseq.setelement(8.5); // Any object can be added. Integer iref = (Integer) intseq.getelement(); // ClassCastException at runtime. Khalid Azim Mughal Java Brand Generics 11/40 Example of (naive) generic code: SimpleSeq public class SimpleSeq<T> { private T element; // Data private SimpleSeq<T> tail; // Rest of the sequence SimpleSeq(T element, SimpleSeq<T> tail) { this.element = element; this.tail = tail; public void setelement(t obj) { element = obj; public T getelement() { return element; public void settail(simpleseq<t> tail) { this.tail = tail; public SimpleSeq<T> gettail() { return this.tail; //... // Client code: declaring references and instantiating objects of generic classes SimpleSeq<Integer> intseq = new SimpleSeq<Integer>(10, null); // (1) SimpleSeq<Double> doubleseq = new SimpleSeq<Double>(20.5,null); // (2) SimpleSeq<Number> numseqa = new SimpleSeq<Number>(30.5, null); // (3) SimpleSeq<Number> numseqb = new SimpleSeq<Number>(30.5, numseqa); // (3) //SimpleSeq<Number> numseqc = new SimpleSeq<Number>(40.5, intseq); // (4) Huh? //SimpleSeq<Number> numseqd = doubleseq; // (5) Huh? Khalid Azim Mughal Java Brand Generics 12/40

7 Example of (naive) generic code: SimpleSeq (cont.) The generic type SimpleSeq<T> allows only a sequence of a specific type to be maintained. The scope of the type parameter T is the declaration of the generic type. All occurrences of the Object class in the LegacySeq class have been replaced by the type parameter T in the SimpleSeq class. The usage of the class name SimpleSeq is parameterized by the type parameter T in the class declaration. The type parameter T binds to the actual type parameter specified in the invocation of the generic type. Note that in the implementation of the generic type SimpleSeq<T>, we never invoke methods on objects of the type parameter T. This is not always the case in implementing generic types. Khalid Azim Mughal Java Brand Generics 13/40 No Subtype Covariance for "Pure" Parameterized Types Number Number[] SimpleSeq<Number> Integer Integer[] SimpleSeq<Integer> What is the problem? SimpleSeq<Integer> intseq = new SimpleSeq<Integer>(64, null); SimpleSeq<Number> numseq = intseq; // (1) DISALLOWED: compile-time error numseq.setelement(3.14); // (2) No runtime type info available Integer iref = intseq.getelement(); // (3) Runtime type error Khalid Azim Mughal Java Brand Generics 14/40

8 INCREASING EXPRESSIVE POWER WITH WILDCARD TYPE PARAMETERS Defining Variant Parametric Types with Wildcards Type Parameter Upper and Lower Bounds Understanding Subtype-Supertype Relationships involving Generic Types Using Wildcards Comparison to Interfaces Declaring References with Wild Cards Usage Restrictions Using Multiple Bounds Running example classes: class Seq<T> {... class SafeSeq<T> extends Seq<T> {... Khalid Azim Mughal Java Brand Generics 15/40 Type Specification Overview Name Syntax Semantics Description Subtype Covariance Subtype Contravariance Subtype Bivariance Subtype Invariance <? extends T> Any subtype of T Wildcard with upper bound <? super T> Any supertype of T Wildcard with lower bound <?> Any type Unbounded Wildcard <T> Only type T "Pure" generics Khalid Azim Mughal Java Brand Generics 16/40

9 Subtype Covariance: <? extends T> The subtype covariance relation is represented by the following bounded wildcard: <? extends T>? denotes an unknown type. T is called the upper bound. The wildcard <? extends T> means that any subtype of T (or T itself) is acceptable as an actual type parameter in the wildcard invocation. Example: The wildcard <? extends Number> denotes a family of subtypes of Number. The invocation Seq<? extends Number> denotes a set of invocations of Seq for types that are subtypes of Number. Seq<? extends Number>... Seq<Number> Seq<? extends Integer> Seq<Integer> Khalid Azim Mughal Java Brand Generics 17/40 Subtype Contravariance: <? super T> The subtype contravariance relation is represented by the following bounded wildcard: <? super T> T is called the lower bound. The wildcard <? super T> means that any supertype of T (or T itself) is acceptable as an actual type parameter in the wildcard invocation. Example: The wildcard <? super Integer> denotes a family of supertypes of Integer. The wildcard invocation Seq<? super Integer> denotes a set of invocations of Seq for types that are supertypes of Integer. Seq<? super Integer> Seq<Integer> Seq<? super Number> Seq<? super Comparable> Seq<Number> Seq<? super Object> Seq<Comparable> Seq<Object> Khalid Azim Mughal Java Brand Generics 18/40

10 Subtype Bivariance: <?> The subtype bivariance relation is represented by the unbounded wildcard, <?>. By definition, the bivariance relation is covariant and contravariant. It denotes the family of all types. Example: The wildcard invocation Seq<?> denotes the set of invocations of Seq for any type, i.e. denotes a Seq of anything. Subtype Invariance: <T> The subtype invariance relation is represented by <T>, there T is a specific type. The notation <T> means that only T is acceptable as an actual type parameter in the invocation. Example: "Pure" Generics The invocation Seq<Integer> denotes a set containing only the instantiation of Seq for the specified type parameter. Khalid Azim Mughal Java Brand Generics 19/40 Variant Parametric Type Hierarchy (partial view) Object Number Seq<?> Integer Seq<? extends Number> Seq<? super Integer> Seq<Number> Seq<? extends Integer> Seq<? super Number> Seq<Integer> Seq<? super Object> Seq<Object> Khalid Azim Mughal Java Brand Generics 20/40

11 Generic Class Seq<T> public class Seq<T> { private T element; // Data private Seq<? extends T> tail; // Rest of the sequence Seq(T element, Seq<? extends T> tail) { this.element = element; this.tail = tail; public void setelement(t obj) { element = obj; public T getelement() { return element; public void settail(seq<? extends T> tail) { this.tail = tail; public Seq<? extends T> gettail() { return this.tail; public void sort(comparator<? super T> comp) {/*...*/ public String tostring() { return this.element.tostring() + (this.tail == null? "" : ", " + this.tail); //... Khalid Azim Mughal Java Brand Generics 21/40 Reference Declarations With Wildcards A wildcard can be used for declaration of references, but not for creating objects. Seq<? extends Number> numseq = new Seq<?>(2006, null); // Compile-time error The type of the object cannot be deduced. Such a reference can refer to an object whose type is a parameterized type in the set of invocations of the generic type denoted by the wildcard invocation. i.e. assignment compatibility is according to the variant parametric type hierarchy of the wildcard instantiations. Seq<Integer> intseq = new Seq<Integer>(10, null); Seq<Number> numseqc = new Seq<Number>(50.5, intseq); //Seq<Number> numseqd = intseq; // Compile-time error Seq<? extends Number> numseqe = intseq; Seq<? extends Integer> numseqf = null; Seq<? super Integer> numseqg = new Seq<Integer>(2004, null); See class Seq<T> for examples of wildcards in reference declarations, formal method parameters and method return types. Declaring references with wildcards is analogous to declaring references of interface types, as interfaces cannot be instantiated. Khalid Azim Mughal Java Brand Generics 22/40

12 Access Restrictions on References declared with <?> Seq<Integer> intseq = new Seq<Integer>(2005, null); Seq<?> seq = new Seq<Integer>(2006, intseq); // (1) // seq.setelement(new Integer(2007)); // (2) Compile-time error // seq.settail(intseq); // (3) Compile-time error seq.settail(null); // (4) Object ref = seq.getelement(); // (5) seq = seq.gettail(); // (6) String str = seq.tostring(); // (7) Not ok to write, except nulls. Cannot call a method that has a formal parameter whose type cannot be determined from the actual type parameter (in this case <?>), i.e. it is some unknown type. Ok to read Objects. For example, can call a method whose result type is determined to be an unknown type, as it will always be some Object. Khalid Azim Mughal Java Brand Generics 23/40 Access Restrictions on References declared with <? extends T> Seq<Integer> intseq = new Seq<Integer>(2005, null); Seq<? extends Number> numseq = new Seq<Integer>(2006, intseq); // (1) // numseq.setelement(new Integer(2007)); // (2) Compile-time error // numseq.settail(intseq); // (3) Compile-time error numseq.settail(null); // (4) Number ref = numseq.getelement(); // (5) numseq = numseq.gettail(); // (6) String str2 = numseq.tostring(); // (7) Not ok to write, except null. Cannot call a method that has a formal parameter whose type cannot be determined from the actual type parameter (in this case <? extends Number>), i.e. it is some unknown subtype of Number. Ok to read Numbers. For example, can call a method whose result type is determined to be the upper bound of the wildcard. Khalid Azim Mughal Java Brand Generics 24/40

13 Access Restrictions on References declared with <? super T> Seq<Integer> intseq = new Seq<Integer>(2005, null); Seq<? super Integer> seq = new Seq<Integer>(2006, intseq); // (1) seq.setelement(new Integer(2007)); // (2) // seq.settail(intseq); // (3) Compile-time error seq.settail(null); // (4) Object ref = seq.getelement(); // (5) // seq = seq.gettail(); // (6) Compile-time error String str = seq.tostring(); // (7) Ok to write Integers. Safe to write for lower bound. Ok only to read Objects. Not safe to assume any other type but Object. Khalid Azim Mughal Java Brand Generics 25/40 Flexibility with Wildcard Type Parameters Consider the following two implementations of the sort() method for the generic class Seq<T>: public void sort(comparator<t> comp) {/*...*/ // Alt. (1) public void sort(comparator<? super T> comp) {/*...*/ // Alt. (2) Client code: Seq<String> strseq = new Seq<String>("aha", new Seq<String>("aho", null)); strseq.sort(string.case_insensitive_order); // Comparator<String> is ok for (1) // and (2). strseq.sort(new Comparator<Object>() { // Comparator<Object> is not ok public int compare(object o1, Object o2) // for (1) and but is ok for (2). {return...; ); Alt. 2 gives greater flexibility in choice of comparator. Khalid Azim Mughal Java Brand Generics 26/40

14 Type Parameters with Multiple Bounds A type parameter T can have multiple bounds: T extends MyClass & Comparable<T> & Serializable Example of usage: class SomeClass<T extends MyClass & Comparable<T> & Serializable> { /*...*/ If the raw type of a bound is a superclass, then it can only be specified as the first bound and there can only be one such bound (as a subclass can only extend one immediate superclass). A type parameter T having multiple bounds is a subtype of all of the types denoted by the individual bounds. The raw type of an individual bound cannot be used with different arguments: E extends Object & Comparable<E> & Serializable & Comparable<String> // Not OK. The first bound is used as the type erasure for the type parameter T (see discussion on type erasures). Note the use of the type parameter T in the bound Comparable<T>. In the invocation SomeClass<MyType>, the compiler ensures that MyType also implements Comparable<MyType>. Khalid Azim Mughal Java Brand Generics 27/40 Type Parameters within Bounds class Foo<E extends Comparable> { Foo<Comparable> compref = new Foo<Integer>(); // (1) Not Ok Foo<? super Number> numref = null; // (2) Not within bound! numref = new Foo<Integer>(); // (3) Not ok Foo<? super Integer> intref = new Foo<Integer>(); // (4) Ok Foo<? extends Integer> intref2 = new Foo<Integer>(); // (5) 0k In (2), the parameterized type Foo<? super Number> is the set of all invocations for any type that is a supertype of Number and a subtype of Comparable. There is no such type. In (4), the parameterized type Foo<? super Integer> is the set of all invocations for any type that is a supertype of Integer and a subtype of Comparable. Integer and Comparable are such types. In (5), the parameterized type Foo<? extends Integer> is the set of all invocations for any type that is a subtype of Integer and a subtype of Comparable. Integer is such a type. Khalid Azim Mughal Java Brand Generics 28/40

15 Generic Interfaces Specification of a generic interface is analogous to that of a generic class: public interface Comparable<E> { int compareto(e thingy); Invocation of a generic interface is analogous to that of a generic class, but it is done in conjunction with a class implementing the interface: // Non-generic class implements generic interface class Node implements Comparable<Node> { //... int compareto(node thingy) {... //... // Generic class implements generic interface public class ArrayList<E> extends AbstractList<E> implements List<E>, RandomAccess, Cloneable, Serializable { //... Khalid Azim Mughal Java Brand Generics 29/40 GENERIC METHODS Declaring Generic Methods Calling Generic Methods Limitations on Generic Methods and Wild Card Usage Khalid Azim Mughal Java Brand Generics 30/40

16 Declaring Generic Methods A generic method (a.k.a. polymorphic method) is implemented like an ordinary method, except that a type parameter is specified immediately preceding the return type. Examples: Two attempts at writing a generic method that returns the "maximum" of two objects. static <T> T max1(t obj1, T obj2) { // Note the type parameter. T result = obj1; if (obj1.compareto(obj2) < 0) // Compiler-time error: method compareto(t) not found result = obj2; return result; static <T extends Comparable<T>> T max2(t obj1, T obj2) { T result = obj1; if (obj1.compareto(obj2) < 0) // OK result = obj2; return result; A generic method need not be in a generic class. If declared in a generic class, a generic method can also use the type parameters of the class. Khalid Azim Mughal Java Brand Generics 31/40 Calling Generic Methods A generic method can be called like an ordinary method, without any actual type parameter. The parameter type (and the return type) is inferred from the type of the actual parameters. int maxint = max2(12,23); // OK String maxstr = max2("aha", "madonna"); // OK Number numresult= max2(new Integer(12), new Double(23.0)); // Compile-time error Calling generic methods whose parameters have parameterized types. // Generic Methods: static <T> void merge1 (Seq<T> s1, Seq<T> s2) { /*...*/ ; static <T> void merge2 (Seq<T> s1, Seq<? extends T> s2) { /*...*/ ; static <T> void merge3 (Seq<T> s1, Seq<? super T> s2) { /*...*/ ; // Client code: Seq<Number> numseq = new Seq<Number>(31.4, null); Seq<Integer> intseq = new Seq<Integer>(2004, null); // merge1(numseq, intseq); // Compile-time error merge2(numseq, intseq); // OK, T is Number // merge2(intseq, numseq); // Compile-time error merge3(intseq, numseq); // OK, T is Integer // merge3(numseq, intseq); // Compile-time error Khalid Azim Mughal Java Brand Generics 32/40

17 Generic Methods and Wildcards Dependency between the type of the parameter obj and that of the element type of the collection c is not captured by the wildcard <?> in this nongeneric method: static boolean add (Object obj, Collection<?> c) { return c.add(obj); // Compile-time error: // Cannot add to a collection of unknown type Dependency between the type of the parameter obj and that of the element type of the collection c is captured by the type parameter in this generic method. static <T> boolean add (T obj, Collection<T> c) { return c.add(obj); // OK Khalid Azim Mughal Java Brand Generics 33/40 TRANSLATION BY TYPE ERASURE Translating Type Parameters, Wildcards and Generic Methods Mixing Generic Types and Raw Types Khalid Azim Mughal Java Brand Generics 34/40

18 Post-Erasure Code for the Generic Class Seq<T> Note how the type parameter has been erased and all usage of the type parameter replaced by the type Object. public class Seq { private Object element; private Seq tail; Seq(Object obj, Seq seq) { element = obj; tail = seq; public void setelement(object obj) { element = obj; public Object getelement() { return element; public void settail(seq seq) { tail = seq; public Seq gettail() { return tail; public String tostring() { return... //... A tool like jad can be used to decompile the class files to see the post-erasure code ( Khalid Azim Mughal Java Brand Generics 35/40 Example of Post-Erasure Code for Overriding Bridge methods are inserted in subclasses to ensure that overriding works correctly. public class Age implements Comparable<Age> { int age; Age(int age) { this.age = age; public int compareto(age that) { return this.age - that.age; public class Age implements Comparable { int age; Age(int age) { this.age = age; public int compareto(age that) { return this.age - that.age; public int compareto(object obj){ return compareto((age)obj); Khalid Azim Mughal Java Brand Generics 36/40

19 Mixing Raw Types and Generic Types For backward compatibility, use of the raw type of a generic type is allowed, i.e. a generic type can be used without its type parameters. Assignments from raw types to parameterized types generate a warning, as in (2). Using raw type references to call methods whose signature uses type parameters generates a warning, as in (5). Note the ClassCastException in (6) at runtime because of the method call in (5). import java.util.*; public class Legacy { public static void main(string[] args) { List<String> strlist = new ArrayList<String>(); // (0) List list = strlist; // (1) Assignment to nongeneric reference is ok. strlist = list; // (2) warning: unchecked assignment strlist.add("aha"); // (3) Method call typesafe. // strlist.add(23); // (4) Compile-time error list.add(23); // (5) warning: [unchecked] unchecked call to add(e) // as a member of the raw type java.util.list System.out.println(strList.get(1).length()); // (6) ClassCastException Khalid Azim Mughal Java Brand Generics 37/40 Post-Erasure Code for the class Legacy It is instructive to compare the corresponding lines of code in the pre-erasure and post-erasure versions of the class Legacy. Note the cast inserted to convert from Object type to String type in (6'). public class Legacy { //... public static void main(string[] args) { ArrayList strlist = new ArrayList(); // (0') ArrayList list = strlist; // (1') strlist = list; // (2') strlist.add("aha"); // (3') list.add(integer.valueof(23)); // (5') System.out.println(((String)strList.get(1)).length()); // (6') Khalid Azim Mughal Java Brand Generics 38/40

20 OTHER IMPLICATIONS AND RESTRICTIONS REGARDING JAVA GENERICS A type parameter cannot be referenced in a static context. Runtime type check with instanceof and casting on generic types have no meaning. Arrays of generic types are not permitted. Foo<?>[] ref1 = new Foo<?>[10]; // OK Foo<Integer>[] ref2 = new Foo<?>[10]; // Declaration not ok Foo<? extends Number>[] ref3 = new Foo<Integer>[10]; // Not ok on both counts For overloading, it is not enough to use wildcards for formal parameter types. Generic classes can be extended: class Parent<A, B> { /*...*/ class Child<X, Y, Z> extends Parent<Z, Comparable> { /*...*/ The subclass provides the actual type parameters for the superclass. For overriding, the return type of the method in the subclass can now be identical or a subtype of the return type of the method in the superclass. A generic class cannot be a subclass of Throwable. Type parameters are allowed in the throws clause, but not for the parameter of the catch block. Varargs with a parameterized type are not legal. Khalid Azim Mughal Java Brand Generics 39/40 FURTHER STUDY AND RESOURCES 1. JSR 14 Add Generic Types To The Java Programming Language: Final Public Draft. ( 2. The Java Language Specification. JLS Maintenance Page at books/jls/jls-maintenance.html. 3. Gilad Bracha. Generics in the Java Programming Language, July ( java.sun.com/j2se/1.5/pdf/generics-tutorial.pdf) 4. Gilad Bracha, Mads Torgersen. New Features in the Java Programming Language. JavaOne Conference, Session TS-3216, San Francisco, USA. June Mads Torgersen, Christian Plesner Hansen, Peter von der Ahé, Erik Ernst, Gilad Bracha, Neal Gafter. Adding Wildcards to the Java Programming Language. SAC 04 (ACM Symposium on Applied Computing), March 2004, Nicosia, Cyprus. Have generic fun! Khalid Azim Mughal Java Brand Generics 40/40

Introducing Generics

Introducing Generics Generics Introducing Generics Generics allow reference types (classes, interfaces, and array types) and methods to be parameterized with type information. An abstract data type (ADT) defines both the types

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

Java 5 New Language Features

Java 5 New Language Features Java 5 New Language Features Ing. Jeroen Boydens, BLIN prof dr. ir. Eric Steegmans http://users.khbo.be/peuteman/java5/ Enterprise Programming Last session. Jeroen Boydens 1. JDK v1.4: assert 2. Generics

More information

COMP1008 An overview of Polymorphism, Types, Interfaces and Generics

COMP1008 An overview of Polymorphism, Types, Interfaces and Generics COMP1008 An overview of Polymorphism, Types, Interfaces and Generics Being Object-Oriented Exploiting the combination of: objects classes encapsulation inheritance dynamic binding polymorphism pluggability

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

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

Collections Algorithms

Collections Algorithms Collections Algorithms 1 / 11 The Collections Framework A collection is an object that represents a group of objects. The collections framework allows different kinds of collections to be dealt with in

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

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

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

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

Weiss Chapter 1 terminology (parenthesized numbers are page numbers) Weiss Chapter 1 terminology (parenthesized numbers are page numbers) assignment operators In Java, used to alter the value of a variable. These operators include =, +=, -=, *=, and /=. (9) autoincrement

More information

Operators and Expressions

Operators and Expressions Operators and Expressions Conversions. Widening and Narrowing Primitive Conversions Widening and Narrowing Reference Conversions Conversions up the type hierarchy are called widening reference conversions

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

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

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

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

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

Agenda. Objects and classes Encapsulation and information hiding Documentation Packages

Agenda. Objects and classes Encapsulation and information hiding Documentation Packages Preliminaries II 1 Agenda Objects and classes Encapsulation and information hiding Documentation Packages Inheritance Polymorphism Implementation of inheritance in Java Abstract classes Interfaces Generics

More information

Advanced Topics in Java and on Security in Systems Effective Generics. Eirik Eltvik 26 th of February 2007

Advanced Topics in Java and on Security in Systems Effective Generics. Eirik Eltvik 26 th of February 2007 Advanced Topics in Java and on Security in Systems Effective Generics Eirik Eltvik 26 th of February 2007 Taking care when calling Legacy code Checks at compile-time is not always appropriate When? Legacy

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

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

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

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

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

CS61B Lecture #23. Today: Java support for generic programming. Readings for today: A Java Reference, Chapter 10. CS61B Lecture #23 Announcements: Josh s office hours are now back in his office. HW6 now due Saturday. Partial solar eclipse tomorrow, starting at 1:52PM. Next one in August, 2017. See http://www.timeanddate.com/eclipse/list.html

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

301AA - Advanced Programming [AP-2017]

301AA - Advanced Programming [AP-2017] 301AA - Advanced Programming [AP-2017] Lecturer: Andrea Corradini andrea@di.unipi.it Tutor: Lillo GalleBa galleba@di.unipi.it Department of Computer Science, Pisa Academic Year 2017/18 AP-2018-15: Java

More information

Argument Passing All primitive data types (int etc.) are passed by value and all reference types (arrays, strings, objects) are used through refs.

Argument Passing All primitive data types (int etc.) are passed by value and all reference types (arrays, strings, objects) are used through refs. Local Variable Initialization Unlike instance vars, local vars must be initialized before they can be used. Eg. void mymethod() { int foo = 42; int bar; bar = bar + 1; //compile error bar = 99; bar = bar

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

Java: introduction to object-oriented features

Java: introduction to object-oriented features Chair of Software Engineering Carlo A. Furia, Marco Piccioni, Bertrand Meyer Java: introduction to object-oriented features Chair of Software Engineering Carlo A. Furia, Marco Piccioni, Bertrand Meyer

More information

Outline. Java Models for variables Types and type checking, type safety Interpretation vs. compilation. Reasoning about code. CSCI 2600 Spring

Outline. Java Models for variables Types and type checking, type safety Interpretation vs. compilation. Reasoning about code. CSCI 2600 Spring Java Outline Java Models for variables Types and type checking, type safety Interpretation vs. compilation Reasoning about code CSCI 2600 Spring 2017 2 Java Java is a successor to a number of languages,

More information

Universe Type System for Eiffel. Annetta Schaad

Universe Type System for Eiffel. Annetta Schaad Universe Type System for Eiffel Annetta Schaad Semester Project Report Software Component Technology Group Department of Computer Science ETH Zurich http://sct.inf.ethz.ch/ SS 2006 Supervised by: Dipl.-Ing.

More information

Generics. Computer Science and Engineering College of Engineering The Ohio State University. Lecture 10

Generics. Computer Science and Engineering College of Engineering The Ohio State University. Lecture 10 Generics Computer Science and Engineering College of Engineering The Ohio State University Lecture 10 A Simple Component Client-side view: Pencil interface Pencil { String tostring(); void setcolor(colors

More information

Contents. Figures. Tables. Examples. Foreword. Preface. 1 Basics of Java Programming 1. xix. xxi. xxiii. xxvii. xxix

Contents. Figures. Tables. Examples. Foreword. Preface. 1 Basics of Java Programming 1. xix. xxi. xxiii. xxvii. xxix PGJC4_JSE8_OCA.book Page ix Monday, June 20, 2016 2:31 PM Contents Figures Tables Examples Foreword Preface xix xxi xxiii xxvii xxix 1 Basics of Java Programming 1 1.1 Introduction 2 1.2 Classes 2 Declaring

More information

COP 3330 Final Exam Review

COP 3330 Final Exam Review COP 3330 Final Exam Review I. The Basics (Chapters 2, 5, 6) a. comments b. identifiers, reserved words c. white space d. compilers vs. interpreters e. syntax, semantics f. errors i. syntax ii. run-time

More information

Java Design Goals. Lecture 32: Java. Java Original implementations slow! Exceptions & Subtyping. - void method readfiles() throws IOException {...}!

Java Design Goals. Lecture 32: Java. Java Original implementations slow! Exceptions & Subtyping. - void method readfiles() throws IOException {...}! Java Design Goals Lecture 32: Java CSC 131 Fall, 2014 Kim Bruce Portability across platforms Reliability Safety (no viruses) Dynamic Linking Multithreaded execution Simplicity and Familiarity Efficiency

More information

Class, Variable, Constructor, Object, Method Questions

Class, Variable, Constructor, Object, Method Questions Class, Variable, Constructor, Object, Method Questions http://www.wideskills.com/java-interview-questions/java-classes-andobjects-interview-questions https://www.careerride.com/java-objects-classes-methods.aspx

More information

301AA - Advanced Programming [AP-2017]

301AA - Advanced Programming [AP-2017] 301AA - Advanced Programming [AP-2017] Lecturer: Andrea Corradini andrea@di.unipi.it Tutor: Lillo GalleBa galleba@di.unipi.it Department of Computer Science, Pisa Academic Year 2017/18 AP-2017-14: Java

More information

CS412/CS413. Introduction to Compilers Tim Teitelbaum. Lecture 17: Types and Type-Checking 25 Feb 08

CS412/CS413. Introduction to Compilers Tim Teitelbaum. Lecture 17: Types and Type-Checking 25 Feb 08 CS412/CS413 Introduction to Compilers Tim Teitelbaum Lecture 17: Types and Type-Checking 25 Feb 08 CS 412/413 Spring 2008 Introduction to Compilers 1 What Are Types? Types describe the values possibly

More information

Polymorphism. return a.doublevalue() + b.doublevalue();

Polymorphism. return a.doublevalue() + b.doublevalue(); Outline Class hierarchy and inheritance Method overriding or overloading, polymorphism Abstract classes Casting and instanceof/getclass Class Object Exception class hierarchy Some Reminders Interfaces

More information

Inheritance. Inheritance allows the following two changes in derived class: 1. add new members; 2. override existing (in base class) methods.

Inheritance. Inheritance allows the following two changes in derived class: 1. add new members; 2. override existing (in base class) methods. Inheritance Inheritance is the act of deriving a new class from an existing one. Inheritance allows us to extend the functionality of the object. The new class automatically contains some or all methods

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

UMCS. Annales UMCS Informatica AI 4 (2006) Polymorphism prose of Java programmers. Zdzisław Spławski *

UMCS. Annales UMCS Informatica AI 4 (2006) Polymorphism prose of Java programmers. Zdzisław Spławski * Annales Informatica AI 4 (2006) 291-303 Polymorphism prose of Java programmers Zdzisław Spławski * Institute of Computer Science, Wrocław University of Technology, Wybrzeże Wyspiańskiego 27, 50-370 Wrocław,

More information

More than you ever wanted to know about. Java Generics. Jeff Meister CMSC 420 Summer 2007

More than you ever wanted to know about. Java Generics. Jeff Meister CMSC 420 Summer 2007 More than you ever wanted to know about Java Generics Jeff Meister CMSC 420 Summer 2007 The obligatory review of the boring stuff, or GENERICS: A YOUNG LADY S ILLUSTRATED PRIMER IN FOUR SLIDES Java 1.4:

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

Chapter 11: Collections and Maps

Chapter 11: Collections and Maps Chapter 11: Collections and Maps Implementing the equals(), hashcode() and compareto() methods A Programmer's Guide to Java Certification (Second Edition) Khalid A. Mughal and Rolf W. Rasmussen Addison-Wesley,

More information

Programming Kotlin. Familiarize yourself with all of Kotlin s features with this in-depth guide. Stephen Samuel Stefan Bocutiu BIRMINGHAM - MUMBAI

Programming Kotlin. Familiarize yourself with all of Kotlin s features with this in-depth guide. Stephen Samuel Stefan Bocutiu BIRMINGHAM - MUMBAI Programming Kotlin Familiarize yourself with all of Kotlin s features with this in-depth guide Stephen Samuel Stefan Bocutiu BIRMINGHAM - MUMBAI Programming Kotlin Copyright 2017 Packt Publishing First

More information

Advances in Programming Languages: Generics, interoperability and implementation

Advances in Programming Languages: Generics, interoperability and implementation Advances in Programming Languages: Generics, interoperability and implementation Stephen Gilmore The University of Edinburgh February 1, 2007 Understanding generic code Generic Java extends Java with generic

More information

On the Algorithm for Specializing Java Programs with Generic Types

On the Algorithm for Specializing Java Programs with Generic Types On the Algorithm for Specializing Java Programs with Generic Types Daniel Selifonov, Nathan Dahlberg, Elena Machkasova Computer Science Discipline University of Minnesota Morris Morris MN, 56267 selif004,dahlb061,elenam@umn.edu

More information

Generics with Type Bounds

Generics with Type Bounds Generics with Type Bounds Computer Science and Engineering College of Engineering The Ohio State University Lecture 27 Generic Methods Like classes, methods can be generic class ArrayOps { //ordinary nongeneric

More information

Object-Oriented Programming

Object-Oriented Programming Object-Oriented Programming Object-Oriented Software Design Responsibilities: Divide the work into different actors, each with a different responsibility. These actors become classes. Independence: Define

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

Language Features. 1. The primitive types int, double, and boolean are part of the AP

Language Features. 1. The primitive types int, double, and boolean are part of the AP Language Features 1. The primitive types int, double, and boolean are part of the AP short, long, byte, char, and float are not in the subset. In particular, students need not be aware that strings are

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

25. Generic Programming

25. Generic Programming 25. Generic Programming Java Fall 2009 Instructor: Dr. Masoud Yaghini Generic Programming Outline Polymorphism and Generic Programming Casting Objects and the instanceof Operator The protected Data and

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

Cracking the New Sun Certified Programmer for Java 2 Platform 1.5 Exam

Cracking the New Sun Certified Programmer for Java 2 Platform 1.5 Exam Cracking the New Sun Certified Programmer for Java 2 Platform 1.5 Exam Khalid Azim Mughal Department of Informatics University of Bergen khalid@ii.uib.no http://www.ii.uib.no/~khalid Version date: 2005-09-04

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

COURSE 5 PROGRAMMING III OOP. JAVA LANGUAGE

COURSE 5 PROGRAMMING III OOP. JAVA LANGUAGE COURSE 5 PROGRAMMING III OOP. JAVA LANGUAGE PREVIOUS COURSE CONTENT Generics Defining a generic Run-time behavior Collections List Set Map COUSE CONTENT Collections Utilities classes Aggregate Operations

More information

Java Inheritance. Written by John Bell for CS 342, Spring Based on chapter 6 of Learning Java by Niemeyer & Leuck, and other sources.

Java Inheritance. Written by John Bell for CS 342, Spring Based on chapter 6 of Learning Java by Niemeyer & Leuck, and other sources. Java Inheritance Written by John Bell for CS 342, Spring 2018 Based on chapter 6 of Learning Java by Niemeyer & Leuck, and other sources. Review Which of the following is true? A. Java classes may either

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

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

interface MyAnno interface str( ) val( )

interface MyAnno interface str( ) val( ) Unit 4 Annotations: basics of annotation-the Annotated element Interface. Using Default Values, Marker Annotations. Single-Member Annotations. The Built-In Annotations-Some Restrictions. 1 annotation Since

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

CS-202 Introduction to Object Oriented Programming

CS-202 Introduction to Object Oriented Programming CS-202 Introduction to Object Oriented Programming California State University, Los Angeles Computer Science Department Lecture III Inheritance and Polymorphism Introduction to Inheritance Introduction

More information

COMP6700/2140 Generic Methods

COMP6700/2140 Generic Methods COMP6700/2140 Generic Methods Alexei B Khorev and Josh Milthorpe Research School of Computer Science, ANU March 2017 Alexei B Khorev and Josh Milthorpe (RSCS, ANU) COMP6700/2140 Generic Methods March 2017

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

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

CS 320 Introduction to Software Engineering Spring 2017

CS 320 Introduction to Software Engineering Spring 2017 Recap: Are UML diagrams useful? CS 320 Introduction to Software Engineering Spring 2017 March 01, 2017 Communication Forward design (before coding) brainstorm ideas (on whiteboard or paper) draft and iterate

More information

JDK 7 (2011.7) knight76.tistory.com Knight76 at gmail.com

JDK 7 (2011.7) knight76.tistory.com Knight76 at gmail.com JDK 7 (2011.7) JDK 7 #2 Project Coin knight76.tistory.com Knight76 at gmail.com 1 Project Coin 2 Project Leader Joseph D. Darcy( ) IDEA 2 27, 2009 3 30, 2009 (open call) 70 jdk 7, Language, The Java programming-language

More information

Object Oriented Programming: Based on slides from Skrien Chapter 2

Object Oriented Programming: Based on slides from Skrien Chapter 2 Object Oriented Programming: A Review Based on slides from Skrien Chapter 2 Object-Oriented Programming (OOP) Solution expressed as a set of communicating objects An object encapsulates the behavior and

More information

23. Generics and Adapters

23. Generics and Adapters COMP 401 Prasun Dewan 1 23. Generics and Adapters The term generic implies unspecialized/common behavior. In an object oriented language, it seems to apply to the class Object, which describes the behavior

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

Chapter 5 Object-Oriented Programming

Chapter 5 Object-Oriented Programming Chapter 5 Object-Oriented Programming Develop code that implements tight encapsulation, loose coupling, and high cohesion Develop code that demonstrates the use of polymorphism Develop code that declares

More information

What are Generics? e.g. Generics, Generic Programming, Generic Types, Generic Methods

What are Generics? e.g. Generics, Generic Programming, Generic Types, Generic Methods What are Generics? e.g. Generics, Generic Programming, Generic Types, Generic Methods 6 Defining the idea Behind Java Generics Data Types are now used as TypeParameters 7 Defining the idea Behind Java

More information

Design issues for objectoriented. languages. Objects-only "pure" language vs mixed. Are subclasses subtypes of the superclass?

Design issues for objectoriented. languages. Objects-only pure language vs mixed. Are subclasses subtypes of the superclass? Encapsulation Encapsulation grouping of subprograms and the data they manipulate Information hiding abstract data types type definition is hidden from the user variables of the type can be declared variables

More information

A declaration may appear wherever a statement or expression is allowed. Limited scopes enhance readability.

A declaration may appear wherever a statement or expression is allowed. Limited scopes enhance readability. Scope vs. Lifetime It is usually required that the lifetime of a run-time object at least cover the scope of the identifier. That is, whenever you can access an identifier, the run-time object it denotes

More information

DOWNLOAD PDF CORE JAVA APTITUDE QUESTIONS AND ANSWERS

DOWNLOAD PDF CORE JAVA APTITUDE QUESTIONS AND ANSWERS Chapter 1 : Chapter-wise Java Multiple Choice Questions and Answers Interview MCQs Java Programming questions and answers with explanation for interview, competitive examination and entrance test. Fully

More information

Primitive Java Generic Class

Primitive Java Generic Class Primitive Java Generic Class 1 A buffer pool is a data structure that caches records retrieved from a disk file, in order to improve an application's performance. Typically, the pool stores some sort of

More information

Contents. I. Classes, Superclasses, and Subclasses. Topic 04 - Inheritance

Contents. I. Classes, Superclasses, and Subclasses. Topic 04 - Inheritance Contents Topic 04 - Inheritance I. Classes, Superclasses, and Subclasses - Inheritance Hierarchies Controlling Access to Members (public, no modifier, private, protected) Calling constructors of superclass

More information

CSE 331 Software Design & Implementation

CSE 331 Software Design & Implementation CSE 331 Software Design & Implementation Hal Perkins Winter 2018 Generics UW CSE 331 Winter 2018 1 Varieties of abstraction Abstraction over computation: procedures (methods) int x1, y1, x2, y2; Math.sqrt(x1*x1

More information

Computer Science II (20073) Week 1: Review and Inheritance

Computer Science II (20073) Week 1: Review and Inheritance Computer Science II 4003-232-01 (20073) Week 1: Review and Inheritance Richard Zanibbi Rochester Institute of Technology Review of CS-I Hardware and Software Hardware Physical devices in a computer system

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

Subclass Gist Example: Chess Super Keyword Shadowing Overriding Why? L10 - Polymorphism and Abstract Classes The Four Principles of Object Oriented

Subclass Gist Example: Chess Super Keyword Shadowing Overriding Why? L10 - Polymorphism and Abstract Classes The Four Principles of Object Oriented Table of Contents L01 - Introduction L02 - Strings Some Examples Reserved Characters Operations Immutability Equality Wrappers and Primitives Boxing/Unboxing Boxing Unboxing Formatting L03 - Input and

More information

CMSC 132: Object-Oriented Programming II

CMSC 132: Object-Oriented Programming II CMSC 132: Object-Oriented Programming II Java Support for OOP Department of Computer Science University of Maryland, College Park Object Oriented Programming (OOP) OO Principles Abstraction Encapsulation

More information

CONTENTS. PART 1 Structured Programming 1. 1 Getting started 3. 2 Basic programming elements 17

CONTENTS. PART 1 Structured Programming 1. 1 Getting started 3. 2 Basic programming elements 17 List of Programs xxv List of Figures xxix List of Tables xxxiii Preface to second version xxxv PART 1 Structured Programming 1 1 Getting started 3 1.1 Programming 3 1.2 Editing source code 5 Source code

More information

CS260 Intro to Java & Android 03.Java Language Basics

CS260 Intro to Java & Android 03.Java Language Basics 03.Java Language Basics http://www.tutorialspoint.com/java/index.htm CS260 - Intro to Java & Android 1 What is the distinction between fields and variables? Java has the following kinds of variables: Instance

More information

Type Hierarchy. Lecture 6: OOP, autumn 2003

Type Hierarchy. Lecture 6: OOP, autumn 2003 Type Hierarchy Lecture 6: OOP, autumn 2003 The idea Many types have common behavior => type families share common behavior organized into a hierarchy Most common on the top - supertypes Most specific at

More information

Principles of Computer Science

Principles of Computer Science Principles of Computer Science Java Generics 19/09/2013 CSCI 2010 - Java Generics - F.Z. Qureshi 1 Topics Benefits of generics Using generic classes and interfaces Declaring generic classes and interfaces

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

Pieter van den Hombergh Richard van den Ham. March 1, 2018

Pieter van den Hombergh Richard van den Ham. March 1, 2018 ,, Pieter van den Hombergh Richard van den Ham Fontys Hogeschool voor Techniek en Logistiek Type : Upper March 1, 2018 /FHTenL, March 1, 2018 1/29 Topics, Type : Upper Type : Lower Bounds, accepting things

More information

Object typing and subtypes

Object typing and subtypes CS 242 2012 Object typing and subtypes Reading Chapter 10, section 10.2.3 Chapter 11, sections 11.3.2 and 11.7 Chapter 12, section 12.4 Chapter 13, section 13.3 Subtyping and Inheritance Interface The

More information

Inheritance and Polymorphism

Inheritance and Polymorphism Inheritance and Polymorphism Dr. M. G. Abbas Malik Assistant Professor Faculty of Computing and IT (North Jeddah Branch) King Abdulaziz University, Jeddah, KSA mgmalik@kau.edu.sa www.sanlp.org/malik/cpit305/ap.html

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

HAS-A Relationship. Association is a relationship where all objects have their own lifecycle and there is no owner.

HAS-A Relationship. Association is a relationship where all objects have their own lifecycle and there is no owner. HAS-A Relationship Association is a relationship where all objects have their own lifecycle and there is no owner. For example, teacher student Aggregation is a specialized form of association where all

More information