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.
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.
Slides prepared by Rose Williams, Binghamton University Chapter 13 Interfaces and Inner Classes.
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,
Options for User Input Options for getting information from the user –Write event-driven code Con: requires a significant amount of new code to set-up.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Chapter 17 Animated Version Generics and Type Safety.
1 Genericity Parameterizing by Type. 2 Generic Class One that is parameterized by type  Works when feature semantics is common to a set of types On object.
Appendix A.2: Review of Java and Object-Oriented Programming: Part 2 “For the object-oriented project, remember that the primary unit of decomposition.
“is a”  Define a new class DerivedClass which extends BaseClass class BaseClass { // class contents } class DerivedClass : BaseClass { // class.
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.
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.
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.
1 Generics and Using a Collection Generics / Parameterized Classes Using a Collection Customizing a Collection using Inheritance Inner Classes Use of Exceptions.
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.
Introduction to Generics
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.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 9 Inheritance and.
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 4 Generic Vector Class. Agenda A systemic problem with Vector of Object – Several approaches at a solution – Generic structures Converting classes.
Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
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.
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.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 10 Java Fundamentals Objects/ClassesMethods.
OOP Tirgul 10. What We’ll Be Seeing Today  Generics – A Reminder  Type Safety  Bounded Type Parameters  Generic Methods  Generics and Inner Classes.
Chapter 5: Enhancing Classes
ADT’s, Collections/Generics and Iterators
More on Java Generics Multiple Generic Types Bounded Generic Types
Java Programming Language
CISC124 Assignment 4 on Inheritance due next Monday, the 12th at 7pm.
Implementing Non-Static Features
Generic programming in Java
Chapter 19 Generics.
Chapter 21 Generics.
Chapter 19 Generics Jung Soo (Sue) Lim Cal State LA.
Object Oriented Programming in java
Java Programming Language
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 new T( … ); }

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 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

9 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

11 Parameterized Classes Static members can’t use generics because there is only one copy of the code for all of the parameterized class objects instantiated with possibly different generic types public class BadExample { private static T count; // error public static T method() // error {…} }

12 Parameterized Classes Don’t invoke static methods of parameterized classes with a generic type specified // the following is an error int n = BadExample.method(); // a static method must be invoked as int n = BadExample.method(); But it is OK to instantiate the class with a generic to use its non-static methods

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 13

14 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

15 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 16

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 17

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 } 18

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 19

20 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

21 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."); }