CMSC 202. Generics II

Similar documents
Generalized Code. Fall 2011 (Honors) 2

Introduction to Generics. Defining a Class with a Type Parameter

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

ECE 122. Engineering Problem Solving with Java

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

public static <E extends Comparable<? super E>>void BubbleSort(E[] array )

First IS-A Relationship: Inheritance

Day 4. COMP1006/1406 Summer M. Jason Hinek Carleton University

HAS-A Relationship. Association is a relationship where all objects have their own lifecycle and there is no owner.

COMP 110/L Lecture 19. Kyle Dewey

Object-Oriented Programming More Inheritance

HAS-A Relationship. If A uses B, then it is an aggregation, stating that B exists independently from A.

More Relationships Between Classes

Inheritance and Polymorphism

Object-Oriented Concepts

What is Inheritance?

Comp 249 Programming Methodology

Inheritance in java is a mechanism in which one object acquires all the properties and behaviors of parent object.

Object-Oriented ProgrammingInheritance & Polymorphism

Rules and syntax for inheritance. The boring stuff

Polymorphism. Agenda

Full file at Chapter 2 - Inheritance and Exception Handling

More About Objects. Zheng-Liang Lu Java Programming 255 / 282

HAS-A Relationship. Association is a relationship where all objects have their own lifecycle and there is no owner.

CMSC 341. Nilanjan Banerjee

CMSC 132: Object-Oriented Programming II. Interface

CS Programming I: Inheritance

Binghamton University. CS-140 Fall Dynamic Types

Instance Members and Static Members

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

COMP 250 Fall inheritance Nov. 17, 2017

COMP 110/L Lecture 20. Kyle Dewey

Java Fundamentals (II)

Example: Count of Points

Inheritance, Polymorphism, and Interfaces

Programming Language Concepts Object-Oriented Programming. Janyl Jumadinova 28 February, 2017

Create a Java project named week10

Homework 6. Yuji Shimojo CMSC 330. Instructor: Prof. Reginald Y. Haseltine

More on Objects in JAVA TM

CMSC201 Computer Science I for Majors

Programming using C# LECTURE 07. Inheritance IS-A and HAS-A Relationships Overloading and Overriding Polymorphism

Class Hierarchy and Interfaces. David Greenstein Monta Vista High School

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

Lesson 10A OOP Fundamentals. By John B. Owen All rights reserved 2011, revised 2014

Object Orientated Programming Details COMP360

CS 12 Fall 2003 Solutions for mid-term exam #2

Inheritance (Outsource: )

Inheritance. Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L

Practice for Chapter 11

Overview of OOP. Dr. Zhang COSC 1436 Summer, /18/2017

Exercise: Singleton 1

Subtype Polymorphism

Inheritance (Part 5) Odds and ends

Practice Questions for Final Exam: Advanced Java Concepts + Additional Questions from Earlier Parts of the Course

CS 61B Discussion 5: Inheritance II Fall 2014

Need to store a list of shapes, each of which could be a circle, rectangle, or triangle

Inheritance. Notes Chapter 6 and AJ Chapters 7 and 8

Inheritance and Polymorphism

Topic 5: Abstract Classes & Interfaces

Example: Count of Points

Inheritance and object compatibility

Chapter 7. Inheritance

Object Fundamentals Part Three. Kenneth M. Anderson University of Colorado, Boulder CSCI 4448/6448 Lecture 4 09/06/2007

CSC 273 Data Structures

Chapter 11 Inheritance and Polymorphism. Motivations. Suppose you will define classes to model circles,

Arrays Classes & Methods, Inheritance

Polymorphism. Final Exam. November 26, Method Overloading. Quick Review of Last Lecture. Overriding Methods.

Collections, Maps and Generics

CS111: PROGRAMMING LANGUAGE II

EECS2030 Week 7 worksheet Tue Feb 28, 2017

Java Object Oriented Design. CSC207 Fall 2014

Inheritance (Part 2) Notes Chapter 6

Inheritance and Polymorphism

Overview. Lecture 7: Inheritance and GUIs. Inheritance. Example 9/30/2008

Data Structures (list, dictionary, tuples, sets, strings)

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

Overriding Variables: Shadowing

Lecture 18 CSE11 Fall 2013 Inheritance

Inheritance & Polymorphism

Object Oriented Programming: Based on slides from Skrien Chapter 2

What s Conformance? Conformance. Conformance and Class Invariants Question: Conformance and Overriding

24. Inheritance. Java. Fall 2009 Instructor: Dr. Masoud Yaghini

Lecture 21: The Many Hats of Scala: OOP 10:00 AM, Mar 14, 2018

Introduction to Object-Oriented Programming

Brief Summary of Java

Chapter 10 Inheritance and Polymorphism. Dr. Hikmat Jaber

Abstract Classes. Abstract Classes a and Interfaces. Class Shape Hierarchy. Problem AND Requirements. Abstract Classes.

Comp 249 Programming Methodology Chapter 8 - Polymorphism

22. Inheritance. Java. Summer 2008 Instructor: Dr. Masoud Yaghini

ENCAPSULATION AND POLYMORPHISM

Critique this Code. Hint: It will crash badly! (Next slide please ) 2011 Fawzi Emad, Computer Science Department, UMCP

Polymorphism. CMSC 330: Organization of Programming Languages. Two Kinds of Polymorphism. Polymorphism Overview. Polymorphism

Reusability. Relationships among Objects. Relationships among Objects

Subtypes and Subclasses

INHERITANCE AND EXTENDING CLASSES

Inf1-OP. Classes with Stuff in Common. Inheritance. Volker Seeker, adapting earlier version by Perdita Stevens and Ewan Klein.

Programming overview

Generics with Type Bounds

C++ Inheritance and Encapsulation

Inf1-OP. Inheritance. Volker Seeker, adapting earlier version by Perdita Stevens and Ewan Klein. March 12, School of Informatics

Transcription:

CMSC 202 Generics II

Generic Sorting We can now implement sorting functions that can be used for any class (that implements Comparable). The familiar insertion sort is shown below.!! public static <T extends Comparable<T>> void insertionsort(t[] array) {! "for (int i = 1; i < array.length; i++) {! " "int j = i;! " "T item = array[i];! " "while ((j > 0) && (array[j - 1].compareTo(item) > 0)) {! " " "array[j] = array[j - 1];! " " "j--;! " "}! " "array[j] = item;! "}! }

Generics and Hierarchies What if we want a somewhat specialized container that assumes the objects it holds are part of a hierarchy so that the container code can assume the existence of a particular method? Let s look at Animals, Dogs, and Cats class Animal { public void speak(){...}... } class Dog extends Animal {...} class Cat extends Animal {...} We would like to create a container named Zoo to hold some animals that speak.

Zoo<T> If we define the Zoo like this public class Zoo< T > we ll get a compiler error when we try to invoke the speak( ) method. Not all classes provide a method called speak( ). Only Animals provide speak( ). The solution is to place a bounds on T. The Zoo can only contain Animals or any type that inherits from Animal. public class Zoo< T extends Animal > The phrase T extends Animal means Animal or any subtype of Animal

Generics and Hierarchy For example, suppose we revisit the Animals. Each animal has a weight and a name. Let s say two Dogs (or two Cats) are the equal if they have the same name and weight. class Animal { private String name; private int weight;...} class Dog extends Animal implements Comparable<Dog>{... } class Cat extends Animal implements Comparable<Cat>{... } Since Dog implements comparable<dog> it s clear you can compare Dogs with Dogs, but not with Cats We can use our insertionsort method with Dogs or with Cats

Sorting Dogs public void main(string[] args){ Dog[] dogs = new Dog[42]; // put some dogs in the array //.. } // use insertion sort to sort dogs MyClass.insertionSort(dogs);

Generics and Hierarchies What happens if we want to sort a class in an inheritance hierarchy, but some ancestor of the class implements comparable, and not the class itself? But suppose we wanted compare all Animals using only their weight. The class definitions would look something like this class Animal implements Comparable<Animal> {...} class Dog extends Animal {... } class Cat extends Animal {... } Since Animal implements comparable, any two Animals can be compared (albeit only by weight). The problem is now that we can t use insertionsort to sort an array of Dogs because Dog doesn t explicitly implement Comparable (it s inherited from Animal)

New insertionsort The solution is to use a wildcard when defining insertionsort? super T is read as any supertype of T. Now, because Dog extends Animal which implements Comparable, insertionsort can be used with an array of Dogs as before. public static <T extends Comparable<? super T>>! void insertionsort(t[] array){! for (int i = 1; i < array.length; i++){! int j = i;! T B = array[i];! while ((j > 0) && (array[j-1].compareto(b) > 0)){! array[j] = array[j-1];! j--;! }! array[j] = B;! }! }

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

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

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

Generic Methods The type parameter must be placed (in angular brackets) after all the modifiers, and before the returned type public class Utility {... public static <T> T getmidpoint( T[ ] array) { return array[array.length / 2]; } } public static <T> T getfirst( T[ ] a ) { return a[0]; }...

Generic Methods When one of these generic methods is invoked, the method name is prefaced with the type to be plugged in, enclosed in angular brackets String s = Utility.<String>getMidPoint(arrayOfStrings); double first = Utility.<Double>getFirst (arrayofdoubles);

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: A and 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 B is a subclass of class A

The Commonly Used Generic Ordered Pair Class (1 of 4)

A Generic Ordered Pair Class ( 2 of 4)

A Generic Ordered Pair Class ( 3 of 4)

A Generic Ordered Pair Class (4 of 4)

A Derived Generic Class (1 of 2) In this example UnorderedPair overrides equals( ) that was inherited from Pair

A Derived Generic Class (Part 2 of 2)

Using UnorderedPair (Part 1 of 2)

Using UnorderedPair (Part 2 of 2)