Introduction to Generics. Defining a Class with a Type Parameter

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

Generalized Code. Fall 2011 (Honors) 2

CMSC 202. Generics II

Modulo I Java Generics

Generics method and class definitions which involve type parameters.

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

Introduction to Programming Using Java (98-388)

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

Program Correctness and Efficiency. Chapter 2

Comp 249 Programming Methodology Chapter 9 Exception Handling

Generics and the. ArrayList Class CHAPTER

Object Orientation Fourth Story. Bok, Jong Soon

AP Computer Science Chapter 10 Implementing and Using Classes Study Guide

Chapter 9. Exception Handling. Copyright 2016 Pearson Inc. All rights reserved.

Arrays Classes & Methods, Inheritance

Chapter 5: Procedural abstraction. Function procedures. Function procedures. Proper procedures and function procedures

Comp 249 Programming Methodology

Module 11. Collections and Iterators. Adapted from Absolute Java, Rose Williams, Binghamton University

7. C++ Class and Object

IC Language Specification

Java 5 New Language Features

CMSC 132: Object-Oriented Programming II

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

Java Primer 1: Types, Classes and Operators

CS111: PROGRAMMING LANGUAGE II

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

Java Fundamentals (II)

A Short Summary of Javali

Chapter 14 Abstract Classes and Interfaces

CS260 Intro to Java & Android 03.Java Language Basics

3.Constructors and Destructors. Develop cpp program to implement constructor and destructor.

Java Object Oriented Design. CSC207 Fall 2014

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

Java Generics. Lecture CS1122 Summer 2008

Zhifu Pei CSCI5448 Spring 2011 Prof. Kenneth M. Anderson

Module 5. Arrays. Adapted from Absolute Java, Rose Williams, Binghamton University

Programming with Java

Java Threads and intrinsic locks

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

Object oriented programming. Instructor: Masoud Asghari Web page: Ch: 3

Declarations and Access Control SCJP tips

Programming overview

Chapter 6 Introduction to Defining Classes

2. The object-oriented paradigm

Points To Remember for SCJP

Array. Prepared By - Rifat Shahriyar

Harvard School of Engineering and Applied Sciences Computer Science 152

Full file at Chapter 2 - Inheritance and Exception Handling

4. Java language basics: Function. Minhaeng Lee

Array Basics: Outline. Creating and Accessing Arrays. Creating and Accessing Arrays. Arrays (Savitch, Chapter 7)

Java. Representing Data. Representing data. Primitive data types

Java: introduction to object-oriented features

ASSIGNMENT NO 13. Objectives: To learn and understand concept of Inheritance in Java

Chapter 7. Inheritance

Chapter 4 Defining Classes I

Use the scantron sheet to enter the answer to questions (pages 1-6)

Java Bytecode (binary file)

Inheritance, Polymorphism, and Interfaces

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

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

Classes. Logical method to organise data and functions in a same structure. Also known as abstract data type (ADT).

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

Exam Duration: 2hrs and 30min Software Design

Lecture 02, Fall 2018 Friday September 7

CS 231 Data Structures and Algorithms, Fall 2016

26. Interfaces. Java. Fall 2009 Instructor: Dr. Masoud Yaghini

Introduction Welcome! Before you start Course Assessments The course at a glance How to pass M257

Computational Expression

Java Applets. Last Time. Java Applets. Java Applets. First Java Applet. Java Applets. v We created our first Java application

Annotation File Specification

Software Paradigms (Lesson 3) Object-Oriented Paradigm (2)

C++ Programming Fundamentals

25. Interfaces. Java. Summer 2008 Instructor: Dr. Masoud Yaghini

Creating Java Programs with Greenfoot

Static Semantics. Winter /3/ Hal Perkins & UW CSE I-1

Java: exceptions and genericity

A Third Look At Java. Chapter Seventeen Modern Programming Languages, 2nd ed. 1

Grammars and Parsing, second week

Object Oriented Programming

CONSTRUCTOR & Description. String() This initializes a newly created String object so that it represents an empty character sequence.

Technical Questions. Q 1) What are the key features in C programming language?

Datatypes, Variables, and Operations

SSOL Language Reference Manual

9/10/2018 Programming Data Structures Inheritance

Inheritance. Lecture 11 COP 3252 Summer May 25, 2017

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

INHERITANCE. Spring 2019

CMSC 341. Nilanjan Banerjee

What are the characteristics of Object Oriented programming language?

More on Objects in JAVA TM

Generics Concurrency Exceptions (examples in C++, Java, & Ada)

Chapter 4. Defining Classes I

Exception in thread "main" java.lang.arithmeticexception: / by zero at DefaultExceptionHandling.main(DefaultExceptionHandling.

Introduction to Java

Fall 2017 CISC124 9/16/2017

c) And last but not least, there are javadoc comments. See Weiss.

BTE2313. Chapter 2: Introduction to C++ Programming

Java Language Basics: Introduction To Java, Basic Features, Java Virtual Machine Concepts, Primitive Data Type And Variables, Java Operators,

Java for Non Majors Spring 2018

Brief Summary of Java

Transcription:

Introduction to Generics Beginning with version 5.0, Java allows class and method definitions that include parameters for types Such definitions are called generics Generic programming with a type parameter enables code to be written that applies to any class Already have been using generics E.g. ArrayList<BaseType> alist = new ArrayList<BaseType>(); 14-1 Defining a Class with a Type Parameter 14-2 1

Class Definition with a Type Parameter A class that is defined with a parameter for a type is called a generic class or a parameterized class The type parameter is included in angular brackets after the class name in the class definition heading Any non-keyword identifier can be used for the type parameter, but by convention, the parameter starts with an uppercase letter The type parameter can be used like other types used in the definition of a class 14-3 Tip: Compile with the -Xlint Option There are many pitfalls that can be encountered when using type parameters Compiling with the -Xlintoption will provide more informative diagnostics of any problems or potential problems in the code javac Xlint Sample.java 14-4 2

A Generic Ordered Pair Class (Part 1 of 4) 14-5 A Generic Ordered Pair Class (Part 2 of 4) 14-6 3

A Generic Ordered Pair Class (Part 3 of 4) 14-7 A Generic Ordered Pair Class (Part 4 of 4) 14-8 4

Using Our Ordered Pair Class (Part 1 of 3) 14-9 Using Our Ordered Pair Class (Part 2 of 3) 14-10 5

Using Our Ordered Pair Class (Part 3 of 3) 14-11 Pitfall: A Generic Constructor Name Has No Type Parameter Although the class name in a parameterized class definition has a type parameter attached, the type parameter is not used in the heading of the constructor definition public Pair<T>() A constructor can use the type parameter as the type for a parameter of the constructor, but in this case, the angular brackets are not used public Pair(T first, T second) However, when a generic class is instantiated, the angular brackets are used Pair<String> pair = new Pair<String>("Happy", "Day"); 14-12 6

Pitfall: A Primitive Type Cannot be Plugged in for a Type Parameter The type plugged in for a type parameter must always be a reference type It cannot be a primitive type such as int, double, or char However, now that Java has automatic boxing, this is not a big restriction Use Integer, Double, Char Note: reference types can include arrays 14-13 Pitfall: A Type Parameter Cannot Be Used Everywhere a Type Name Can Be Used Within the definition of a parameterized class definition, there are places where an ordinary class name would be allowed, but a type parameter is not allowed In particular, the type parameter cannot be used in simple expressions using new to create a new object For instance, the type parameter cannot be used as a constructor name or like a constructor: T object = new T(); T[] a = new T[10]; 14-14 7

Pitfall: An Instantiation of a Generic Class Cannot be an Array Base Type Arrays such as the following are illegal: Pair<String>[] a = new Pair<String>[10]; Although this is a reasonable thing to want to do, it is not allowed given the way that Java implements generic classes 14-15 Using Our Ordered Pair Class and Automatic Boxing (Part 1 of 3) 14-16 8

Using Our Ordered Pair Class and Automatic Boxing (Part 2 of 3) 14-17 Using Our Ordered Pair Class and Automatic Boxing (Part 3 of 3) 14-18 9

Pitfall: A Class Definition Can Have More Than One Type Parameter A generic class definition can have any number of type parameters Multiple type parameters are listed in angular brackets just as in the single type parameter case, but are separated by commas 14-19 Multiple Type Parameters (Part 1 of 4) 14-20 10

Multiple Type Parameters (Part 2 of 4) 14-21 Multiple Type Parameters (Part 3 of 4) 14-22 11

Multiple Type Parameters (Part 4 of 4) 14-23 Using a Generic Class with Two Type Parameters (Part 1 of 2) 14-24 12

Using a Generic Class with Two Type Parameters (Part 2 of 2) 14-25 Pitfall: A Generic Class Cannot Be an Exception Class It is not permitted to create a generic class with Exception, Error, Throwable, or any descendent class of Throwable A generic class cannot be created whose objects are throwable public class GEx<T> extends Exception The above example will generate a compiler error message 14-26 13

Bounds for Type Parameters Sometimes it makes sense to restrict the possible types that can be plugged in for a type parameter T For instance, to ensure that only classes that implement the Comparableinterface are plugged in for T, define a class as follows: public class RClass<T extends Comparable> "extends Comparable" serves as a boundon the type parameter T Any attempt to plug in a type for Twhich does not implement the Comparable interface will result in a compiler error message 14-27 Bounds for Type Parameters A bound on a type may be a class name (rather than an interface name) Then only descendent classes of the bounding class may be plugged in for the type parameters public class ExClass<T extends Class1> A bounds expression may contain multiple interfaces and up to one class If there is more than one type parameter, the syntax is as follows: public class Two<T1 extends Class1, T2 extends Class2 & Comparable> 14-28 14

A Bounded Type Parameter 14-29 Tip: Generic Interfaces An interface can have one or more type parameters The details and notation are the same as they are for classes with type parameters 14-30 15

Generics and Methods Consider writing a method that takes an array of objects and a collection and puts all objects in the array into the collection. Here's a first attempt (that doesn t work): static void fromarraytocollection(object[] a, Collection<?> c) { for (Object o : a) { c.add(o); // Compile time error } } Can t put objects of an unknown type into the Collection 14-31 Solution - Generic Methods When a generic class is defined, the type parameter can be used in the definitions of the methods for that generic class In addition, a generic method can be defined that has its own type parameter that is not the type parameter of any class A generic method can be a member of an ordinary class or a member of a generic class that has some other type parameter The type parameter of a generic method is local to that method, not to the class 14-32 16

Generic Methods The type parameter must be placed (in angular brackets) after all the modifiers, and before the returned type public static <T> T genmethod(t[] a) When one of these generic methods is invoked, the method name is prefaced with the type to be plugged in, enclosed in angular brackets (if left off, Java will infer the type) String s = NonG.<String>genMethod(c); 14-33 Generic Collection Example static <T> void fromarraytocollection(t[] a, Collection<T> c) { for (T o : a) { c.add(o); // Correct } } fromarraytocollection(strarray, strcollection) 14-34 17

Inheritance with Generic Classes A generic class can be defined as a derived class of an ordinary class or of another generic class As in ordinary classes, an object of the subclass type would also be of the superclass type Given two classes: Aand B, and given G: a generic class, there is no relationship between G<A>and G<B> This is true regardless of the relationship between class A and B, e.g., if class Bis a subclass of class A 14-35 A Derived Generic Class (Part 1 of 2) 14-36 18

A Derived Generic Class (Part 2 of 2) 14-37 Using UnorderedPair (Part 1 of 2) 14-38 19

Using UnorderedPair (Part 2 of 2) 14-39 20