1 Generics and Using a Collection Generics / Parameterized Classes Using a Collection Customizing a Collection using Inheritance Inner Classes Use of Exceptions.

Slides:



Advertisements
Similar presentations
New features in JDK 1.5 Can these new and complex features simplify Java development?
Advertisements

Java Review Interface, Casting, Generics, Iterator.
CHAPTER 12 GENERICS Introduction to java 1. Assignment 5 Solution See Eclipse.
1 ADT and Data Structure Example Generics / Parameterized Classes Using a Set Implementing a Set with an Array Example: SetADT interface Example: ArraySet.
Generic programming in Java
Inheritance Inheritance Reserved word protected Reserved word super
Slides 4/22 COP Topics Final Exam Review Final Exam The final exam is Friday, April 29 th at 10:00 AM in the usual room No notes, books, calculators,
ITEC200 – Week03 Inheritance and Class Hierarchies.
CSE 143 Lecture 22: Advanced List Implementation (ADTs; interfaces; abstract classes; inner classes; generics; iterators)
George Blank University Lecturer. CS 602 Java and the Web Object Oriented Software Development Using Java Chapter 4.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
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.
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.
Building Java Programs Inner classes, generics, abstract classes reading: 9.6, 15.4,
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Chapter 17 Animated Version Generics and Type Safety.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
CSM-Java Programming-I Spring,2005 Objects and Classes Overview Lesson - 1.
1 Review of Java Higher Level Language Concepts –Names and Reserved Words –Expressions and Precedence of Operators –Flow of Control – Selection –Flow of.
Chapter 3 Introduction to Collections – Stacks Modified
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
Chapter 21 Generics 1. Generics - Overview Generic Methods specify a set of related methods Generic classes specify a set of related types Software reuse.
CreatingClasses-part11 Creating Classes part 1 Barb Ericson Georgia Institute of Technology Dec 2009.
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.
Method Overriding Remember inheritance: when a child class inherits methods, variables, etc from a parent class. Example: public class Dictionary extends.
Generics1 Parametrized classes and methods. Generics2 What are generics Generics are classes or interfaces that can be instantiated with a variety of.
ArrayList, Multidimensional Arrays
Java 5 Part 1 CSE301 University of Sunderland Harry Erwin, PhD.
CSE 143 Lecture 24 Advanced collection classes (ADTs; abstract classes; inner classes; generics; iterators) read 11.1, 9.6, , slides.
1 Collection, Iterable, and Iterator Interfaces The Collection Interface and its Hierarchy The Iterable and Iterator Interfaces For-each Loops with Iterable.
Chapter 14 Abstract Classes and Interfaces. Abstract Classes An abstract class extracts common features and functionality of a family of objects An abstract.
Pengantar OOP Class-Java. 2 Software Development Tools Using Sun Java SDK alone Source File(s) (.java) Programmer Compiler (javac) Class File(s) (.class)
Chapter 3 Collections. Objectives  Define the concepts and terminology related to collections  Explore the basic structures of the Java Collections.
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.
Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
Method Overriding Remember inheritance: when a child class inherits methods, variables, etc from a parent class. Example: public class Dictionary extends.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
Inheritance and Class Hierarchies Chapter 3. Chapter Objectives  To understand inheritance and how it facilitates code reuse  To understand how Java.
Slides prepared by Rose Williams, Binghamton University Chapter 16 Collections and Iterators.
Java How to Program, 9/e © Copyright by Pearson Education, Inc. All Rights Reserved.
JAVA: An Introduction to Problem Solving & Programming, 6 th Ed. By Walter Savitch ISBN © 2012 Pearson Education, Inc., Upper Saddle River,
1 Example: LinkedStack LinkedStack UML Class Diagram LinkedStack Class LinkedStack Attributes/Constructor LinkedStack Methods LinkedStack iterator method.
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.
Notices Assn 2 is due tomorrow, 7pm. Moodle quiz next week – written in the lab as before. Everything up to and including today’s lecture: Big Topics are.
OOP Tirgul 10. What We’ll Be Seeing Today  Generics – A Reminder  Type Safety  Bounded Type Parameters  Generic Methods  Generics and Inner Classes.
JAVA GENERICS Lecture 16 CS2110 – Spring 2016 Photo credit: Andrew Kennedy.
Chapter 5: Enhancing Classes
ADT’s, Collections/Generics and Iterators
More on Java Generics Multiple Generic Types Bounded Generic Types
A tree set Our SearchTree class is essentially a set.
Java Programming Language
CISC124 Assignment 4 on Inheritance due next Monday, the 12th at 7pm.
A tree set Our SearchTree class is essentially a set.
Implementing Non-Static Features
Generic programming in Java
Chapter 19 Generics.
Chapter 21 Generics.
Chapter 19 Generics Jung Soo (Sue) Lim Cal State LA.
Java Programming Language
Review: libraries and packages
Winter 2019 CMPE212 5/3/2019 CMPE212 – Reminders
Chapter 21 Generics.
Chapter 19 Generics.
Chapter 19 Generics.
Presentation transcript:

1 Generics and Using a Collection Generics / Parameterized Classes Using a Collection Customizing a Collection using Inheritance Inner Classes Use of Exceptions Reading: L&C: , 3.5

2 Java Generics In Java 5.0, Sun added a generic feature that had been available in other languages such as C++ (where it is called “Templates”) Although the implementation is different, the user gains the benefit of stronger compiler type checking and simpler coding style (with a reduced number of explicit casts needed)

3 Java Generics The Java implementation was constrained by backward compatibility Code compiled using javac 5.0 and generics had to work on java 4.2 virtual machines The technique used was “type erasure” and one copy of the parameterized class code is accessed with compiler supplied casts Avoids C++ “code bloat” where there are multiple copies of the parameterized code

4 Parameterized Classes Defining a parameterized class: public class Generic { // use T in attribute declarations private T whatIsThis; // use T as a method’s parameter type public void doThis(T input) { … } // use T as a method’s return type public T doThat( … ) { return whatIsThis; }

5 Parameterized Classes Instantiating a parameterized class Generic g = new Generic (); Use methods with objects of the actual type g.doThis(“Hello”); String s = g.doThat( … ); The compiler can verify the correctness of any parameters passed or assignments of the return values No casting of data types should be required (If it is, you aren’t using generics correctly)

6 Parameterized Classes Note: The letter used inside <> is a dummy and can be like C++ or like Sun I prefer to use T based on C++ popularity and that is also what our textbook uses Only reference types - not primitive types - can be used as a generic type Generic g =... // OK Generic g =... // Compile error

7 Parameterized Classes Must use a known class - not dummy letters Generic g = new Generic (); // error Unless in a generic class where T is defined public class AnotherGenericClass { … Generic g = new Generic (); // OK … }

8 Parameterized Classes Sometimes we want to place a constraint on the class that can be used as T We may need T to be a type that implements a specific interface (e.g. Comparable) public class Sorter > { // now our code can call compareTo // method on type T objects here }

9 Parameterized Classes Don’t omit an identified in new code Generic g = new Generic(); // legacy code? Compiler will give incompatible type errors without an explicit cast (narrowing) String s = g.doThat( … ); // error String s = (String) g.doThat( … ); // OK Compiler will give unchecked warnings g.doThis(“Hello”); // warning

10 Parameterized Classes Can’t instantiate arrays of the generic data type without using a “trick” T [] t = new T[10]; // compile error T [] t = (T []) new Object[10]; // OK Can’t instantiate arrays of a parameterized class without using a slightly different “trick” ArrayList [] a = (ArrayList []) new ArrayList[10]; –Just casting a new Object[10] compiles OK but throws an exception at run time (Ouch!)

Parameterized Classes When you use either of the above “tricks”, the compiler will give you an “unchecked” warning Normally, we would “fix” the code to get rid of the warning but here we can’t “fix” it Use the compiler SuppressWarnings directive Place this line ahead of the method That directive will allow a “clean” compilation

Customizing a Collection If we need a collection class that is similar to any library collection class, we can extend it The ArraySet class we need for Bingo Lab 3 is almost the same as the ArrayList class We can extend the ArrayList class without duplicating all of the code in ArrayList class We add attributes and override methods as needed 12

13 Customizing a Collection In Bingo Lab 3, we need a set collection to contain BingoBall objects for drawing numbers randomly You will extend the java.util.ArrayList collection to create an ArraySet collection It needs two features different from ArrayList –Its add method does not allow duplicate objects to be added because no duplicate numbers should be drawn –It has a removeRandom method to draw balls A UML diagram for the Bingo application is shown in the next slide

14 UML Diagram for Bingo Application Bingo BingoBall ArraySet uses + main (args : String[ ]) : void java.utl.ArrayList implements > Iterable extends - rand : Random + add(T element) : boolean + removeRandom() : T

Customizing a Collection We write the code for an ArraySet class: –Include an extends clause for ArrayList –Include an attribute to hold a Random object –Write a constructor to instantiate Random object –Override the ArrayList add method to check for duplicates using parent’s contains method before adding an object (call the parent’s add method) –Add a removeRandom method that calculates a random integer and returns the return value from the parent’s remove method at that integer value 15

Inner Classes Sometimes when we write the code for a collection class, we need an “inner class” as a “helper” to aggregate data elements The outer class is defined in a file with the outer class name plus.java as usual The inner class is defined inside the { } of the public outer class An “inner class” is usually declared private, but can be public if needed 16

Inner Classes A public class with a private inner class public class OuterClass { // outer class attributes and methods private class InnerClass { // inner class attributes and methods } 17

Inner Classes Code outside the public outer class cannot instantiate an instance of a private inner class or use a reference to call its methods Code in the public outer class’s methods can instantiate objects of an inner class and keep or use their references in its own data / code Code in inner class methods can access the attributes or methods of the instance of the public class that instantiated the inner class 18

19 Use of Exceptions In some cases, there may be constraints that prevent the execution of a method for a specific instance of a collection object For example, a remove operation can not be performed on a collection that is empty The remove method for the class may be coded to check for an empty collection If a collection is empty, remove may throw an EmptyCollectionException

20 Use of Exceptions Hence, a method of any class may have a throws clause in its header, e.g. the class’s remove method T remove() throws EmptyCollectionException To throw an exception, the method uses: throw new EmptyCollectionException(“string”); The exception itself is defined as a class: public class EmptyCollectionException extends RuntimeException { public EmptyCollectionException (String coll) { super ("The " + coll + " is empty."); }