Generic Subroutines and Exceptions CS351 – Programming Paradigms.

Slides:



Advertisements
Similar presentations
SCJP 6.0 Lecturer Kuo-Yi Chen 151, 153, 154, 155, 156, 157
Advertisements

Templates in C++. Generic Programming Programming/developing algorithms with the abstraction of types The uses of the abstract type define the necessary.
Review What is a virtual function? What can be achieved with virtual functions? How to define a pure virtual function? What is an abstract class? Can a.
Comp 212: Intermediate Programming Lecture 18 – Java Generics By: Anupam Chanda.
CHAPTER 12 GENERICS Introduction to java 1. Assignment 5 Solution See Eclipse.
Procedures and Control Flow CS351 – Programming Paradigms.
C12, Polymorphism “many forms” (greek: poly = many, morphos = form)
Java Generics.
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.
1 Generics and Using a Collection Generics / Parameterized Classes Using a Collection Customizing a Collection using Inheritance Inner Classes Use of Exceptions.
Stacks. 2 What is a stack? A stack is a Last In, First Out (LIFO) data structure Anything added to the stack goes on the “top” of the stack Anything removed.
1 L39 Generics (1). 2 OBJECTIVES  To create generic methods that perform identical tasks on arguments of different types.  To create a generic Stack.
Data Abstraction and Object- Oriented Programming CS351 – Programming Paradigms.
Slides prepared by Rose Williams, Binghamton University Chapter 16 Collections and Iterators.
30-Jun-15 Generics. Arrays and collections In Java, array elements must all be of the same type: int[] counts = new int[10]; String[] names = { "Tom",
Lecture 9 Concepts of Programming Languages
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.
Inheritance and Polymorphism CS351 – Programming Paradigms.
Generic Java 21/ What is generics? To be able to assign type variables to a class These variables are not bound to any specific type until the.
Passing Other Objects Strings are called immutable which means that once a String object stores a value, it never changes –recall when we passed a message.
“is a”  Define a new class DerivedClass which extends BaseClass class BaseClass { // class contents } class DerivedClass : BaseClass { // class.
Announcements  I will discuss the labtest and the written test #2 common mistakes, solution, etc. in the next class  not today as I am still waiting.
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
Chapter 21 Generics 1. Generics - Overview Generic Methods specify a set of related methods Generic classes specify a set of related types Software reuse.
Programming Languages and Paradigms Object-Oriented Programming (Part II)
Effective Java: Generics Last Updated: Spring 2009.
Generics1 Parametrized classes and methods. Generics2 What are generics Generics are classes or interfaces that can be instantiated with a variety of.
Generics1 Parametrized classes and methods. Generics2 What are generics Generics are classes or interfaces that can be instantiated with a variety of.
Passing Other Objects Strings are called immutable which means that once a String object stores a value, it never changes –recall when we passed a message.
Generics1 Parametrized classes and methods. Generics2 What are generics Generics are classes or interfaces that can be instantiated with a variety of.
1 Generics and Using a Collection Generics / Parameterized Classes Using a Collection Customizing a Collection using Inheritance Inner Classes Use of Exceptions.
Chapter 18 Java Collections Framework
Java 5 Part 1 CSE301 University of Sunderland Harry Erwin, PhD.
Copyright © Curt Hill Generic Classes Template Classes or Container Classes.
G ENERICS I N J AVA BY: Ankit Goyal Sankalp Singh.
BEGINNING PROGRAMMING.  Literally – giving instructions to a computer so that it does what you want  Practically – using a programming language (such.
CS-2851 Dr. Mark L. Hornick 1 Generic Java Classes Implementing your own generic classes.
Lecture 4 Generic programming Advanced Java Programming 1 dr hab. Szymon Grabowski dr inż. Wojciech Bieniecki
1 Methods Introduction to Methods Passing Arguments to a Method More About Local Variables Returning a Value from a Method Problem Solving with Methods.
Session 24 Chapter 12: Polymorphism. Polymorphism polymorphism comes from the Greek root for “many forms” polymorphism is about how we can use different.
ADT data abstraction. Abstraction  representation of concepts by their relevant features only  programming has two major categories of abstraction process.
Static?. Static Not dynamic class Widget { static int s; int d; // dynamic // or instance // variable }
1 CSE 331 Generics (Parametric Polymorphism) slides created by Marty Stepp based on materials by M. Ernst, S. Reges, D. Notkin, R. Mercer, Wikipedia
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.
Generic(Parameterized ) types Mehdi Einali Advanced Programming in Java 1.
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.
Topic: Classes and Objects
Sixth Lecture ArrayList Abstract Class and Interface
Java Primer 1: Types, Classes and Operators
CS 326 Programming Languages, Concepts and Implementation
Introducing Java Generics and Collections
Chapter 20 Generic Classes and Methods
Generics, Lambdas, Reflections
Java Review: Reference Types
Generics.
Chapter 19 Generics Dr. Clincy - Lecture.
Java Programming Language
CISC124 Assignment 4 on Inheritance due next Monday, the 12th at 7pm.
Generics.
Collections Not in our text.
Functional interface.
Generics, Lambdas, Reflections
Java Programming Language
Review of Previous Lesson
Type Conversion It is a procedure of converting one data type values into another data type In C programming language we are having two types of type conversion.
Presentation transcript:

Generic Subroutines and Exceptions CS351 – Programming Paradigms

Motivations Subroutines provide a natural way of abstracting data operations. With large programs containing many methods it is possible that subroutines will be needed to perform similar operations on many different types. Consider some code from any language: String add (String a, String b) return a + b; int add ( int a, int b ) return a + b; double add ( double a, double b) return a + b; What is wrong with this code? Nothing!

Motivations The code is correct but the repetitious operations must be defined statically many times over. We need a form of parametric parameterisation i.e the subroutine should only be written once and be capable of accepting any arguments. This idea is known as generic programming. In Java version 5, generic programming has been added. In C++, generics are known as templates. Other languages that feature generics are Ada, Modula-3 and C#.

Generics Generics are especially helpful for creating container classes. Container classes are data abstractions that hold a collection of objects. The operation of the container class is independent of the type of object stored. Some examples of container classes include…. Stack Queue Set Heap…

Generic Subroutines Generic subroutines are needed in generic classes. They allow a method to be parameterised by a single type. Hence our earlier example becomes vastly simplified: public T add ( T a, T b) return a + b; This code is now identical to the first slide except we now have a generic type T passed as a parameter to the add method. Hence we can now call the code: int c = add( 5, 7 ); double d = add ( 4.5, 6.9 ); String concat = add( “gen”, “erics” );

Implementing Generics In C++, they are a static mechanism. All of the work required to use multiple instances of the generic code is handled by the compiler. The compiler creates a separate copy of the code for every instance. In Java, all instances of the generic code will shae that same code at run-time. If we call some generic parameter, T in Java, this behaves identically to java.lang.Object except that we do not have to use casts.

Generics in C++ The syntax is similar but the behaviour is more flexiable than Java. However it is easier to make mistakes with C++. A generic add method in C++: template T add (T a, T b) { return a+b; } To call the method add(5,6); add(5.6, 7.8); The compiler figures out all of the hard work.

Generics in Java ``Old’’ Java: A Vector of ints: /* Adding to a Vector *//* Removing from a Vector */ Vector v = new Vector(); for ( int z = 0; z<v.size(); z++ ) for ( int i = 0; i < 10; i++ ) int a = ((Integer)v.elementAt(z)).intValue(); v.add(new Integer(i)); Looks very messy especially, the cast involved when reading from the Vector With generics: /* Adding to a Vector *//* Removing from Vector */ Vector v = new Vector (); for (int i = 0; i < 10 ; i++)for (int a : v) v.add(i);

Java Generics : Erasure Generics in Java are defined in terms of type erasure. This means that every generic type parameter is replaced by java.lang.Object and casts back to concrete types are automatically inserted into the code by the compiler. E.g. class choice {public boolean best ( T a, T b ) {} } Is replaced by: class choice {public boolean best ( Object a, Object b ) {} } This is done to provide backwards compatibility with older non generic Java code.

Java Generics Recall the C++ example: template T add (T a, T b) { return a+b; } This allows any number ( int, float, short, double etc ) to be added together. How can we achieve this is Java? public T add ( T a, T b ) { return a+b; } Is this correct?

Java Generics Lets perform the type erasure: public Object add ( Object a, Object b ) { return a+b; } Does this compile? No!, because the + operator is not applicable to Object. We must modify the code to make it typesafe so it can compile:

Java Generics public T add ( T a, T b ) { return a+b; } We have to impose a higher bound on the type passed to the generic method. In this case we are saying that the type passed in will be a subclass of java.lang.Number Will the code compile now? Nope! We still have to make sure that it is typesafe.

Java Generics public T add ( T a, T b ) { if ( T instanceof Integer ) return a.intValue() + b.intValue(); if ( T instanceof Double ) return a.doubleValue() + b.doubleValue(); return null; } public static void main( String args [] ) { int a = add (5, 6); double b = add ( 7.9, 11.3 ); } We are passing ints and doubles to add but the add method takes Integers and Doubles, how is this?