עקרונות תכנות מונחה עצמים תרגול 21: Generics

Slides:



Advertisements
Similar presentations
Abstract Class and Interface
Advertisements

Written by: Dr. JJ Shepherd
Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. Chapter 17 – Generic Programming.
Generics. DCS – SWC 2 Generics In many situations, we want a certain functionality to work for a variety of types Typical example: we want to be able.
CSE 143 Lecture 22: Advanced List Implementation (ADTs; interfaces; abstract classes; inner classes; generics; iterators)
Java Generics.
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.
Class template Describing a generic class Instantiating classes that are type- specific version of this generic class Also are called parameterized types.
CPSC150 Interfaces Chapter CPSC150 Inheritance Review No different than any other class. Has no access to or information about subclasses class.
1 L39 Generics (1). 2 OBJECTIVES  To create generic methods that perform identical tasks on arguments of different types.  To create a generic Stack.
Slides prepared by Rose Williams, Binghamton University Chapter 16 Collections and Iterators.
1 Types Object Oriented Programming Spring 2007.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Chapter 17 Animated Version Generics and Type Safety.
OOP Languages: Java vs C++
CMSC 202 Interfaces. 11/20102 Classes and Methods When a class defines its methods as public, it describes how the class user interacts with the method.
Polymorphism & Interfaces
Generics In Java 1.5 By Manjunath Beeraladinni. Generics ➲ New feature in JDK1.5. ➲ Generic allow to abstract over types. ➲ Generics make the code clearer.
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.
Inheritance, Abstract & Interface Pepper With help from and
 2005 Pearson Education, Inc. All rights reserved Generics.
Generics CSCI 201L Jeffrey Miller, Ph.D. HTTP :// WWW - SCF. USC. EDU /~ CSCI 201 USC CSCI 201L.
Generics and Collections. Introduction Generics New feature of J2SE 5.0 Provide compile-time type safety Catch invalid types at compile time Generic methods.
Parameters… Classes Cont Mrs. C. Furman October 13, 2008.
1 Generics Chapter 21 Liang, Introduction to Java Programming.
G ENERICS I N J AVA BY: Ankit Goyal Sankalp Singh.
CSE 143 Lecture 24 Advanced collection classes (ADTs; abstract classes; inner classes; generics; iterators) read 11.1, 9.6, , slides.
Polymorphism & Methods COMP206 Geoff Holmes & Bernhard Pfahringer (these slides: lots of input from Mark Hall) poly + morphos (greek) “many forms”
©SoftMoore ConsultingSlide 1 Generics “Generics constitute the most significant change in the Java programming language since the 1.0 release.” – Cay Horstmann.
More Java: Static and Final, Abstract Class and Interface, Exceptions, Collections Framework 1 CS300.
1 CSC 2053 New from AutoBoxing 3 Before J2SE 5.0, working with primitive types required the repetitive work of converting between the primitive.
Chapter 11: Advanced Inheritance Concepts. Objectives Create and use abstract classes Use dynamic method binding Create arrays of subclass objects Use.
Interfaces, Classes, Collections School of Engineering and Computer Science, Victoria University of Wellington COMP T2 Lecture 3 Marcus Frean.
עקרונות תכנות מונחה עצמים תרגול 10: Generics. Outline  Generic classes  Generics & Inheritance  Wild Cards  Case study: Generic Graph.
Object orientation and Packaging in Java Object Orientation and Packaging Introduction: After completing this chapter, you will be able to identify.
COMP Inheritance and Polymorphism Yi Hong June 09, 2015.
Inheritance & Polymorphism Android Club Agenda Inheritance Polymorphism.
 Pearson Education, Inc. All rights reserved. 1 Ch 18 Generics OBJECTIVES In this chapter you will learn:  To create generic methods that perform.
Objects First with Java CITS1001 week 4
Modern Programming Tools And Techniques-I
Sixth Lecture ArrayList Abstract Class and Interface
Fundamentals of Java: AP Computer Science Essentials, 4th Edition
Software Development Java Collections
More on Java Generics Multiple Generic Types Bounded Generic Types
Java Generics.
Generic(Parameterized ) Types
Chapter 20 Generic Classes and Methods
Generics and Subtyping
Methods Attributes Method Modifiers ‘static’
A tree set Our SearchTree class is essentially a set.
Java Generics.
Chapter 19 Generics Dr. Clincy - Lecture.
Generics (Parametric Polymorphism)
Java Programming Language
Polymorphism.
CSE 143 Lecture 27: Advanced List Implementation
Lecture 26: Advanced List Implementation
A tree set Our SearchTree class is essentially a set.
Generics.
Data Structures and Database Applications Arrays And Lists
Dynamic Data Structures and Generics
Unit 3 Test: Friday.
Generics, Lambdas, Reflections
Generic Programming.
Chapter 19 Generics.
Objects with ArrayLists as Attributes
CSE 143 Lecture 21 Advanced List Implementation
មជ្ឈមណ្ឌលកូរ៉េ សហ្វវែរ អេច អ ឌី
Presentation transcript:

עקרונות תכנות מונחה עצמים תרגול 21: Generics

Outline Generic classes Generics & Inheritance Wild Cards characters Case study: Generic Graph

Generic Classes – Motivation List v = new ArrayList(); v.add("test"); Integer i = (Integer)v.get(0); => // runtime error List<String> v = new ArrayList<String>(); v.add("test"); Integer i = (Integer)v.get(0); => // compilation error

class name<T1, T2, ..., Tn> { /* ... */ } Generic Classes A class is generic if it declares one or more type variables. A generic class is defined with the following format: class name<T1, T2, ..., Tn> { /* ... */ } The type parameter section, delimited by angle brackets (<>), follows the class name. It specifies the type parameters (also called type variables) T1,T2, ..., and Tn. The type variables can be used as: Method parameters. Return value. Local variables.

Generic Classes – Example public interface List<E> { void add(E x); Iterator<E> iterator(); } public interface Iterator<E> { E next(); boolean hasNext(); public class ArrayList<E> implements List<E> { private E[] _data; ...

Generic Classes vs Concrete Classes Generic Class declaration defines a set of parameterized types, one for each possible invocation of the type parameter section. All compiles to the same .class file. All uses the same .class file at runtime.

Generic Classes VS Concrete Classes (Example) public class ArrayList<E> implements List<E> { private E[] _data; ... } List<String> v; v = new ArrayList<String>(); Generic class Compile to ArrayList.class Concrete class Uses ArrayList.class

Generics & Inheritance

Assignments roles: If a type A is of a sub-class of type B we will mark it as: 𝐴≼𝐵 We can assign (runtime) type A to a (compile time) variable B iff 𝐴≼𝐵

Using wild cards – Motivation 𝐷𝑜𝑔≼𝐴𝑛𝑖𝑚𝑎𝑙 Animal animal; animal = new Dog(); Cat cat = animal; // // compilation error!!! 𝐴𝑛𝑖𝑚𝑎𝑙≼𝐶𝑎𝑡 Vector<Animal> animals; Vector<Cat> cats = new Vector<Cat>(); animals = cats; animals.add(new Dog()); Cat cat = cats.elementAt(0); // // compilation error!!! 𝑉𝑒𝑐𝑡𝑜𝑟<𝐶𝑎𝑡>≼𝑉𝑒𝑐𝑡𝑜𝑟<𝐴𝑛𝑖𝑚𝑎𝑙> 𝐷𝑜𝑔≼𝐴𝑛𝑖𝑚𝑎𝑙

Using wild cards 𝐴≼𝐵 ↛𝐺<𝐴>≼𝐺<𝐵> 𝐴≼𝐵 𝑖𝑚𝑝𝑙𝑖𝑒𝑠: We can read type B from A. We can write type A to B. We will use wild card (?) to represent an unknown type.

Using wild cards ? extends A – a variable type which can only be read from. We can write only null to it. ? super B – a variable type which can only be written to. We can read only Object from it. 𝐴≼𝐵→𝐺<𝐴> ≼𝐺<? 𝑒𝑥𝑡𝑒𝑛𝑑𝑠 𝐵>. 𝐴≼𝐵→𝐺<𝐵> ≼𝐺<?𝑠𝑢𝑝𝑒𝑟 𝐴>.

Using wild cards – example: public static void makeNoise (Vector<Animal> animals) { for (Animal animal:animals) { animal.say(); } { Vector<Cat> cats = new Vector<Cat>(); makeNoise(cats); => Correction: public static void makeNoise (Vector<? extends Animal> animals) // compilation error!!!

Using wild cards – example: Vector<? extends Animal> animals = null; Vector<Cat> cats = new Vector<Cat>(); animals = cats; animals.add(new Dog()); Cat cat = cats.elementAt(0); => // compilation error!!! Correction: animals.add(null); - The only one that allows.

Using wild cards – examples: Vector<? extends Animal> animals = new Vector<Cat>(); Vector<? extends Cat> cats = new Vector<Animal>(); Vector<? super Animal> animals2 = new Vector<Cat>(); Vector<? super Cat> cats2 = new Vector<Animal>(); animals.add(new Cat()); cats.add(new Cat()); animals.add(null); Cat cat = animals.elementAt(0); Animal animal = cats.elementAt(0); Cat cat2 = animals2.elementAt(0); Animal animal2 = animals2.elementAt(0); Object o = animals2.elementAt(0); // compilation error // compilation error // compilation error // compilation error // compilation error // compilation error // compilation error

Question from 2013 test. נתון שהמחלקה Bיורשת מהמחלקה A, והמחלקה G היא גנרית עם פרמטר יחיד. מה צריך להיות הפרמטר X כדי שההשמה הבאה תהיה תקפה ע"פ כללי הטיפוסים של ג'אווה? G<X> g = new G<B>(); א. A ב. extends A ? ג. super A ? ד. super B ? ה. תשובות ב, ד נכונות ו. תשובות א ,ג נכונות

Question from 2013 test. נתון שהמחלקה Bיורשת מהמחלקה A, והמחלקה G היא גנרית עם פרמטר יחיד. מה צריך להיות הפרמטר X כדי שההשמה הבאה תהיה תקפה ע"פ כללי הטיפוסים של ג'אווה? G<X> g = new G<B>(); א. A ב. extends A ? ג. super A ? ד. super B ? ה. תשובות ב, ד נכונות ו. תשובות א ,ג נכונות

Case study: Generic Graph

Graph

Graphs can model The internet Maps Social networks …

Graph Representation

The vertex class

The Graph Class

The Graph Class

Vertex class - code

Graph class - code

DFS Tour

DFS Tour

Execution example

The Weighted interface

Weight query

Usage example

Usage example (cont.)

Exception handling

Exception handling

Summary Generic class ( List<E> ) 𝐴≼𝐵 ↛𝐺<𝐴>≼𝐺<𝐵> ? extends A ? super A

Summary Generic class ( List<E> ) 𝐴≼𝐵 ↛𝐺<𝐴>≼𝐺<𝐵> ? extends A ? super A