Generics.

Slides:



Advertisements
Similar presentations
CHAPTER 12 GENERICS Introduction to java 1. Assignment 5 Solution See Eclipse.
Advertisements

Generic programming in Java
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Chapter 18 – Generic Classes.
Road Map Introduction to object oriented programming. Classes
Java Generics. 2 The Dark Ages: Before Java 5 Java relied only on inclusion polymorphism  A polymorphism code = Using a common superclass Every class.
1 Generics and Using a Collection Generics / Parameterized Classes Using a Collection Customizing a Collection using Inheritance Inner Classes Use of Exceptions.
Chapter 14 Generics and the ArrayList Class Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
1 Chapter 21 Generics. 2 Objectives F To know the benefits of generics (§21.1). F To use generic classes and interfaces (§21.2). F To declare generic.
1 L40 Generics (2). 2 OBJECTIVES  To understand raw types and how they help achieve backwards compatibility.  To use wildcards when precise type information.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Java From Control Structures through Data Structures by.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Chapter 17 Animated Version Generics and Type Safety.
Appendix A.2: Review of Java and Object-Oriented Programming: Part 2 “For the object-oriented project, remember that the primary unit of decomposition.
Java Generics.
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
Chapter 21 Generics 1. Generics - Overview Generic Methods specify a set of related methods Generic classes specify a set of related types Software reuse.
CMSC 202 Generics. Nov Generalized Code One goal of OOP is to provide the ability to write reusable, generalized code. Polymorphic code using.
Method Overriding Remember inheritance: when a child class inherits methods, variables, etc from a parent class. Example: public class Dictionary extends.
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Chapter 10 - Interfaces.
1 Generics Chapter 21 Liang, Introduction to Java Programming.
Introduction to Generics
Lecture 4 Generic programming Advanced Java Programming 1 dr hab. Szymon Grabowski dr inż. Wojciech Bieniecki
Chapter 5 Objects and Classes Inheritance. Solution Assignments 3 & 4 Review in class…..
Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 19 Generics.
©SoftMoore ConsultingSlide 1 Generics “Generics constitute the most significant change in the Java programming language since the 1.0 release.” – Cay Horstmann.
Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
Java Generics. It is nice if we could write a single sort method that could sort array of any type of elements: – Integer array, – String array, Solution:
1 CSC 2053 New from AutoBoxing 3 Before J2SE 5.0, working with primitive types required the repetitive work of converting between the primitive.
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
An Introduction to Java – Part 1 Erin Hamalainen CS 265 Sec 001 October 20, 2010.
Java How to Program, 9/e © Copyright by Pearson Education, Inc. All Rights Reserved.
1 Chapter 21 Generics. 2 Objectives F To use generic classes and interfaces (§21.2). F To declare generic classes and interfaces (§21.3). F To understand.
(C) 2010 Pearson Education, Inc. All rights reserved. Java How to Program, 8/e.
Java Generics. Lecture Objectives To understand the objective of generic programming To be able to implement generic classes and methods To know the limitations.
OOP Tirgul 10. What We’ll Be Seeing Today  Generics – A Reminder  Type Safety  Bounded Type Parameters  Generic Methods  Generics and Inner Classes.
Lecture 7: Arrays Michael Hsu CSULA 3 Opening Problem Read one hundred numbers, compute their average, and find out how many numbers are above the average.
Chapter VII: Arrays.
Java Generics.
Topic: Classes and Objects
Chapter 11 Inheritance and Polymorphism
Final and Abstract Classes
Inheritance and Polymorphism
CIS265/506 Cleveland State University – Prof. Victor Matos
Java Generics.
Chapter 20 Generic Classes and Methods
Generics, Lambdas, Reflections
Interfaces and Inheritance
Continuing Chapter 11 Inheritance and Polymorphism
Chapter 9 Inheritance and Polymorphism
Chapter 19 Generics Dr. Clincy - Lecture.
Generics (Parametric Polymorphism)
Java Programming Language
Polymorphism.
Generics.
Generic programming in Java
Chapter 19 Generics.
Chapter 21 Generics.
Type Safety, Generics, Lambdas, Class Object
CMSC 202 Generics.
Generics, Lambdas, Reflections
Chapter 19 Generics Jung Soo (Sue) Lim Cal State LA.
CSC 220 – Processing Spring, 2017
Class.
Java Programming Language
Chapter 11 Inheritance and Polymorphism Part 2
Review: libraries and packages
Chapter 21 Generics.
Chapter 19 Generics.
Corresponds with Chapter 5
Chapter 19 Generics.
Presentation transcript:

Generics

Contents Introduction Benefits of Generics Generic Classes and Interfaces Generic Methods Wildcard Generic Types Restrictions on Generics

Introduction Enables to create classes, interfaces, and methods in which the type of data upon which they operate is specified as a parameter. Introduced in Java by jdk 1.5. Generics means parameterized types. Generics add the type-safety. Generics add stability to your code by making more of your bugs detectable at compile time.

Why Generics? The functionality of Gen class can be achieved without generics by specifying Object type and using proper casting whenever required. Then why we use Generics? Java compiler does not have knowledge about the type of data actually stored in NonGen. So: Explicit casts must be employed to retrieve the stored data. Several type mismatch errors cannot be found until run time.

Why Generics? list.add("hello"); String s = (String) list.get(0); Stronger type checks at compile time Elimination of casts ArrayList list = new ArrayList(); list.add("hello"); String s = (String) list.get(0); Using generics: List<String> list = new ArrayList<String>(); String s = list.get(0); // no cast Enabling programmers to implement generic algorithms. We can implement generic algorithms that work on collections of different types, can be customized, and are type safe and easier to read.

Advantage of Generics The ability to create type-safe code in which type-mismatch errors are caught at compile time is a key advantage of generics.

Example

Generics Work Only with Objects When declaring an instance of a generic type, the type argument passed to the type parameter must be a class type. Gen<int> strOb = new Gen<int>(53); The above declaration is an error. A reference of one specific version of a generic type is not type compatible with another version of the same generic type. iOb = strOb; // Wrong!

Generic Class

General Form of Generic Class The generics syntax for declaring a generic class: class class-name<type-param-list> { // ... } The syntax for declaring a reference to a generic class: class-name<type-arg-list> var-name = new class-name<type-arg-list>(cons-arg-list);

Generic Class with Multiple Type Parameters

Problem Create a generic class that contains a method that returns the average of an array of numbers of any type, including integers, floats, and doubles.

Possible Solution

Why Error? The compiler has no way to know that you are intending to create Gen class objects using only numeric types. When we try to compile Gen class, an error is reported that indicates that the doubleValue( ) method is unknown. We need some way to tell the compiler that we intend to pass only numeric types to T.

Bounded Types Used to limit the types that can be passed to a type parameter. When specifying a type parameter, we can create an upper bound that declares the super-class from which all type arguments must be derived. <T extends superclass> A bound can include both a class type and one or more interfaces. class Gen<T extends MyClass & MyInterface> Any type argument passed to T must be a subclass of MyClass and implement MyInterface.

Solution

WILD CARD GenericS

Example (comparing object values) method compare(Stats<Integer>) in the type Gen<Integer> is not applicable for the arguments (Gen<Double>)

Memory representation of objects Gen<Integer> obj1 Gen<Double> obj2 Object of Gen<Integer> required

Solution wildcard generic (i.e. it accepts any type)

Problem Create a generic class Stats that contains a method sameAvg( ) that determines whether two different Stats class objects contain arrays that yield the same average or not; no matter what type of numeric data each object holds. For example, if one object contains the double values 1.0, 2.0, and 3.0, and the other object contains the integer values 2, 1, and 3, then the averages will be the same.

Possible Solution method same_Avg(Stats<Integer>) in the type Stats<Integer> is not applicable for the arguments (Stats<Double>)

Why Error? It will work only with the objects of same type. if the invoking object is of type Stats<Integer>, then the parameter ob must also be of type Stats<Integer>.

WildCard Argument The wildcard simply matches the validity of object. The wildcard argument is specified by the ?, and it represents an unknown type. boolean same_Avg(Stats<?> ob) { if(average() == ob.average()) return true; return false; } Important: It is important to understand that the wildcard does not affect what type of Stats class objects can be created. This is governed by the extends clause in the Stats class declaration. The wildcard simply matches any valid Stats class object.

Bounded Wildcards A bounded wildcard is especially important when you are creating a generic type that will operate on a class hierarchy. // Two-dimensional coordinates. class TwoD { int x, y; TwoD(int a, int b) { x = a; y = b; }

Bounded Wildcards // Three-dimensional coordinates. class ThreeD extends TwoD { int z; ThreeD(int a, int b, int c) { super(a, b); z = c; } } // Four-dimensional coordinates. class FourD extends ThreeD { int t; FourD(int a, int b, int c, int d) { super(a, b, c); t = d; }

Bounded Wildcards // This class holds an array of coordinate objects. class Coords<T extends TwoD> { T[] coords; Coords(T[] o) { coords = o; } } Notice that Coords specifies a type parameter bounded by TwoD. static void showXY(Coords<?> c) System.out.println("X Y Coordinates:"); for(int i=0; i < c.coords.length; i++) System.out.println(c.coords[i].x + " " + c.coords[i].y); System.out.println();

Bounded Wildcards Problem Starts if I want to create a methods showXYZ() for ThreeD and FourD Object. static void showXYZ(Coords<? extends ThreeD> c) { System.out.println("X Y Z Coordinates:"); for(int i=0; i < c.coords.length; i++) System.out.println(c.coords[i].x + " " + c.coords[i].y + " " + c.coords[i].z); System.out.println(); }

Generic Method

Generic Method It is possible to declare a generic method that uses one or more type parameters. Methods inside a generic class are automatically generic relative to the type parameters. It is possible to create a generic method that is enclosed within a non- generic class.

Generic Methods The type parameters are declared before the return type of the method. Generic methods can be either static or non-static. <type-param-list> ret-type method-name(param-list) {…} Example: static <T, V extends T> boolean isIn (T x, V[] y) This ability to enforce type safety is one of the most important advantages of generic methods.

Example

Generic Interfaces

Generic Interfaces Generic interfaces are specified just like generic classes.

Generic Interfaces Example: Generic interfaces are specified just like generic classes. Example: interface MinMax<T extends Comparable<T>> { T min(); T max(); } The implementing class must specify the same bound. Once the bound has been established, it need not to be specified again in the implements clause.

class MyClass<T extends Comparable<T>> implements MinMax <T extends Comparable<T>> { //Wrong In general, if a class implements a generic interface, then that class must also be generic, at least to the extent that it takes a type parameter that is passed to the interface. For example, the following attempt to declare MyClass is in error: class MyClass implements MinMax<T> { // Wrong! Because MyClass does not declare a type parameter, there is no way to pass one to MinMax. In this case, the identifier T is simply unknown, and the compiler reports an error. Of course, if a class implements a specific type of generic interface, such as shown here: class MyClass implements MinMax<Integer> { // OK

Generic Interface interface MinMax<T extends Comparable<T>> { T min(); T max(); } class Myclass<T extends Comparable<T>> implements MinMax<T> …

Example

Generic Constructors

Generic Constructors It is possible for constructors to be generic, even if their class is not. Example: class GenCons { private double val; <T extends Number> GenCons(T arg) val = arg.doubleValue(); } void show_val() { System.out.println("val: " + val);

Erasure // Here, T is bound by Object by default. class Gen<T> { T ob; // here, T will be replaced by Object Gen(T o) { ob = o; } // Return ob. T getob() { return ob; } } // Here, T is bound by String. class GenStr<T extends String> { T str; // here, T will be replaced by String GenStr(T o) { str = o; } T getstr() { return str; }

erasure class Gen extends java.lang.Object{ java.lang.Object ob; Gen(java.lang.Object); java.lang.Object getob(); } class GenStr extends java.lang.Object{ java.lang.String str; GenStr(java.lang.String); java.lang.String getstr();

Some Generic Restrictions Type Parameters Can’t Be Instantiated // Can't create an instance of T. class Gen<T> { T ob; Gen() ob = new T(); // Illegal!!! }

Some Generic Restrictions Restrictions on Static Members class Wrong<T> { // Wrong, no static variables of type T. static T ob; // Wrong, no static method can use T. static T getob() { return ob; }

Some Generic Restrictions Generic Array Restrictions // vals = new T[10]; // can't create an array of T // Gen<Integer> gens[] = new Gen<Integer>[10]; // Wrong! it’s valid to declare a reference to an array of type. cannot create generic exception classes. Cannot Instantiate Generic Types with Primitive Types Pair<int, char> p = new Pair<>(8, 'a'); Cannot Create, Catch, or Throw Objects of Parameterized Types