Comp 212: Intermediate Programming Lecture 18 – Java Generics

Slides:



Advertisements
Similar presentations
Java Review Interface, Casting, Generics, Iterator.
Advertisements

Comp 212: Intermediate Programming Lecture 18 – Java Generics By: Anupam Chanda.
METHOD OVERRIDING 1.Sub class can override the methods defined by the super class. 2.Overridden Methods in the sub classes should have same name, same.
Generics and The ArrayList Class
George Blank University Lecturer. CS 602 Java and the Web Object Oriented Software Development Using Java Chapter 4.
Java Generics.
1 Lecture 3 Inheritance. 2 A class that is inherited is called superclass The class that inherits is called subclass A subclass is a specialized version.
CS180 Generics and Type Safety Dynamic Data Structures 3/21/08.
1 Generics, Type Safety, and Dynamic Data Structures.
Java Generics. 2 The Dark Ages: Before Java 5 Java relied only on inclusion polymorphism  A polymorphism code = Using a common superclass Every class.
Slides prepared by Rose Williams, Binghamton University Chapter 13 Interfaces and Inner Classes.
1 Generics and Using a Collection Generics / Parameterized Classes Using a Collection Customizing a Collection using Inheritance Inner Classes Use of Exceptions.
1 CS Generics L. Grewe 2 What is Generics? Data Structures that contain data (such as lists) are not defined to operate over a specific type of.
1 Chapter 21 Generics. 2 Objectives F To know the benefits of generics (§21.1). F To use generic classes and interfaces (§21.2). F To declare generic.
Generic Subroutines and Exceptions CS351 – Programming Paradigms.
Introduction to Methods
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Chapter 17 Animated Version Generics and Type Safety.
Java Generics.
Chapter 21 Generics 1. Generics - Overview Generic Methods specify a set of related methods Generic classes specify a set of related types Software reuse.
Effective Java: Generics Last Updated: Spring 2009.
CMSC 202 Generics. Nov Generalized Code One goal of OOP is to provide the ability to write reusable, generalized code. Polymorphic code using.
1 Generics and Using a Collection Generics / Parameterized Classes Using a Collection Customizing a Collection using Inheritance Inner Classes Use of Exceptions.
Java 5 Part 1 CSE301 University of Sunderland Harry Erwin, PhD.
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Chapter 10 - Interfaces.
Chapter 3 Inheritance and Polymorphism Goals: 1.Superclasses and subclasses 2.Inheritance Hierarchy 3.Polymorphism 4.Type Compatibility 5.Abstract Classes.
1 final (the keyword, not the exam). 2 Motivation Suppose we’ve defined an Employee class, and we don’t want someone to come along and muck it up  E.g.,
Introduction to Generics
CMSC 330: Organization of Programming Languages Java Generics.
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.
Java Generics – Wildcards By: Anupam Chanda. 2 Generics and Subtyping We start to run into some new issues when we do some things that seem “normal”.
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.
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.
Copyright 2006 Pearson Addison-Wesley, 2008, 2012 Joey Paquet 1 Concordia University Department of Computer Science and Software Engineering SOEN6441 –
Java Generics. Lecture Objectives To understand the objective of generic programming To be able to implement generic classes and methods To know the limitations.
Java Generics.
Sixth Lecture ArrayList Abstract Class and Interface
CSC 243 – Java Programming, Spring 2014
Chapter 11 Inheritance and Polymorphism
Inheritance and Polymorphism
Java Generics.
Generics, Lambdas, Reflections
CS/ENGRD 2110 Fall 2017 Lecture 6: Consequence of type, casting; function equals
The fattest knight at King Arthur's round table was Sir Cumference
Interfaces and Inheritance
Continuing Chapter 11 Inheritance and Polymorphism
Generics.
Subroutines Idea: useful code can be saved and re-used, with different data values Example: Our function to find the largest element of an array might.
Object Oriented Programming (OOP) LAB # 8
Chapter 19 Generics Dr. Clincy - Lecture.
More inheritance, Abstract Classes and Interfaces
Java Programming Language
CISC124 Assignment 4 on Inheritance due next Monday, the 12th at 7pm.
Generics.
Generic programming in Java
Defining methods and more arrays
Chapter 19 Generics.
Chapter 21 Generics.
CISC124 Assignment 4 on Inheritance due today at 7pm.
CMSC 202 Generics.
Generics, Lambdas, Reflections
Chapter 19 Generics Jung Soo (Sue) Lim Cal State LA.
CSC 220 – Processing Spring, 2017
Java Programming Language
Chapter 21 Generics.
Chapter 19 Generics.
CMPE212 – Reminders Assignment 4 on Inheritance due next Friday.
Chapter 19 Generics.
Presentation transcript:

Comp 212: Intermediate Programming Lecture 18 – Java Generics By: Anupam Chanda

Today’s Lecture Java generics Syntax and semantics Parameterized classes and methods Compiler provides type safety Syntax and semantics Examples Generics-based implementation of the list framework – next class

Outline Motivation Parameterized classes Parameterized methods Upper bounded wildcards Lower bounded wildcards Unbounded wildcards

Cast Exceptions at Runtime public class OldBox { Object data; public OldBox(Object data) { this.data = data; } public Object getData() { return data; OldBox intBox = new OldBox(42); int x = (Integer) intBox.getData(); OldBox strBox = new OldBox(“Hi”); String s = (String) strBox.getData(); int y = (Integer) strBox.getData(); intBox = strBox; ClassCastException! Compiles but fails at runtime

Naïve Solution public class IntBox { public class StrBox { Integer data; public IntBox(Integer data) { this.data = data; } public Integer getData() { return data; public class StrBox { String data; public StrBox(String data) { this.data = data; } public String getData() { return data; public class FooBox { Foo data; public FooBox(Foo data) { this.data = data; } public Foo getData() { return data; IntBox intBox = new IntBox(42); int x = intBox.getData(); StrBox strBox = new StrBox(“Hi”); String s = strBox.getData(); int y = (Integer) strBox.getData(); intBox = strBox; Errors caught by compiler Infinite many classes possible

Passing Parameters to Methods: An Analogy public abstract class Sum { public static int sum_0_1() { return (0+1); } … public static int sum_15_22() { return (15+22); public abstract class NewSum { public static int sum(int m, int n) { return (m+n); } Methods accept parameters public class NewMain { public static void main(String[] nu) { int j = NewSum.sum(0,1); … int k = NewSum.sum(15,22); } public class Main { public static void main(String[] nu) { int j = Sum.sum_0_1(); … int k = Sum.sum_15_22(); } Pass parameters to methods Bad – infinite many methods

Java Generics: Key Idea Parameterize type definitions Parameterized classes and methods Provide type safety Compiler performs type checking Prevent runtime cast errors

Parameterized Classes public class OldBox { Object data; public OldBox(Object data) { this.data = data; } public Object getData() { return data; public class Box<E> { E data; public Box(E data) { this.data = data; } public E getData() { return data; We want the box to hold a “specific” class – abstractly represented Object does not work as we have seen earlier Solution – parameterize the class definition E refers to a particular type The constructor takes an object of type E, not any object To use this class, E must be replaced with a specific class

How to Use Parameterized Classes public class Box<E> { E data; public Box(E data) { this.data = data; } public E getData() { return data; Box<Integer> intBox = new Box<Integer>(42); int x = intBox.getData();//no cast needed Box<String> strBox = new Box<String>(“Hi”); String s = strBox.getData();//no cast needed Following lines will not compile anymore: String s = (String) intBox.getData(); int y = (Integer) strBox.getData(); intBox = strBox; Runtime errors now converted to compile time errors

When to Use Parameterized Classes Particularly useful for “container” classes Containers hold but do not process data All collections framework classes in Java 5.0 defined using generics See the Java 5.0 API documentation

Parameterized Classes: Syntax Note A class can have multiple parameters, e.g: public class Stuff<A,B,C> { … } Subclassing parameterized classes allowed, e.g: /* Extending a particular type */ class IntBox extends Box<Integer> { … } Or /* Extending a parameterized type */ class SpecialBox<E> extends Box<E> { … } SpecialBox<String> is a subclass of Box<String>. /* Following assignment is legal */ Box<String> sb = new SpecialBox<String>(“Hi”);

Parameterized Classes in Methods A parameterized class is a type just like any other class. It can be used in method input types and return types, e.g: Box<String> aMethod(int i, Box<Integer> b) { … } If a class is parameterized, that type parameter can be used for any type declaration in that class, e.g: public class Box<E> { E data; public Box(E data) { this.data = data; } public E getData() { return data; public void copyFrom(Box<E> b) { this.data = b.getData(); }//We have added an infinite number of types of Boxes //by writing a single class definition

So Far… Type safety violations Using casts Parameterized classes solve this problem Provide type safety Enforced by the compiler Particularly useful for container classes A parameterized class is another type Next – bounded parameterized classes

Bounded Parameterized Types Sometimes we want restricted parameterization of classes. We want a box, called MathBox that holds only Number objects. We can’t use Box<E> because E could be anything. We want E to be a subclass of Number. public class MathBox<E extends Number> extends Box<Number> { public MathBox(E data) { super(data); } public double sqrt() { return Math.sqrt(getData().doubleValue());

Bounded Parameterized Types (Contd.) public class MathBox<E extends Number> extends Box<Number> { public MathBox(E data) { super(data); } public double sqrt() { return Math.sqrt(getData().doubleValue()); 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

Bounded Parameterized Types (Contd.) 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.

Bounded Parameterized Types (Contd.) 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 & …> For instance: interface A { … } interface B { class MultiBounds<T extends A & B> {

So Far… Parameterized classes Bounded parameterized types To restrict parameter types Next – parameterized methods

Parameterized Methods Consider the following class: public class Foo { //Foo is not parameterized public <T> T aMethod(T x) { //will not compile without <T> //to indicate that this is a //parameterized method. return x; } public static void main(String[] args) { Foo foo = new Foo(); int k = foo.aMethod(5); String s = foo.aMethod("abc"); public class Bar<T> { //Bar is parameterized public T aMethod(T x) { return x; } public static void main(String[] args) { Bar<Integer> bar = new Bar<Integer>(); int k = bar.aMethod(5); String s = bar.aMethod("abc"); //Compilation error here Fix foo and vary parameter to aMethod() Once Bar<T> object is fixed, we are locked to a specific T.

Use of Parameterized Methods Adding type safety to methods that operate on different types Return type dependent on input type

So Far… Parameterized classes Bounded parameterized types Parameterized methods Next – wildcards Bounded Upper Lower Unbounded

Upper Bounded Wildcards in Parameterized Types We start to run into some new issues when we do some things that seem “normal”. For instance, the following seems reasonable: Box<Number> numBox = new Box<Integer>(31); Compiler comes back with an “Incompatible Type” error message. This is because numBox can hold only a Number object and nothing else, not even an object of type Integer which is a subclass of Number. The type of numBox we desire is “a Box of any type which extends Number”. Box<? extends Number> numBox = new Box<Integer>(31);

Upper Bounded Wildcards in Parameterized Types (Contd.) public class Box<E> { public void copyFrom(Box<E> b) { this.data = b.getData(); } //We have seen this earlier //We can rewrite copyFrom() so that it can take a box //that contains data that is a subclass of E and //store it to a Box<E> object public class Box<E> { public void copyFrom(Box<? extends E> b) { this.data = b.getData();//b.getData() is a //subclass of this.data } <? extends E> is called “upper bounded wildcard” because it defines a type that is bounded by the superclass E.

Lower Bounded Wildcards in Parameterized Types Suppose we want to write copyTo() that copies data in the opposite direction of copyFrom(). copyTo() copies data from the host object to the given object. This can be done as: public void copyTo(Box<E> b) { b.data = this.getData(); } Above code is fine as long as b and the host are boxes of exactly same type. But b could be a box of an object that is a superclass of E. This can be expressed as: public void copyTo(Box<? super E> b) { b.data = this.getData(); //b.data() is a superclass of this.data() } <? super E> is called a “lower bounded wildcard” because it defines a type that is bounded by the subclass E.

Unbounded Wildcards Use unbounded wildcards when any type parameter works. <?> is used to specify unbounded wildcards. The following are legal statements. Box<?> b1 = new Box<Integer>(31); Box<?> b2 = new Box<String>(“Hi”); b1 = b2; Wildcard capture: The compiler can figure out exactly what type b1 is above from the right hand side of the assignments. This “capturing” of type information means: 1. The type on the left hand doesn’t need to be specified. 2. The compiler can do additional type checks because it knows the type of b1.

Conclusions Java generics Links to tutorials on the lecture page Parameterized classes and methods Type safety Syntax and semantics through examples Links to tutorials on the lecture page Generics-based implementation of the list framework – next class