Generic Programming and Inner classes ge·ner·ic 1a : relating or applied to or descriptive of all members of a genus, species, class, or group : common.

Slides:



Advertisements
Similar presentations
1 Classes and Data Abstraction Chapter What a Class ! ! Specification and implementation Private and public elements Declaring classes data and.
Advertisements

Fields, Constructors, Methods
Abstract Data Types Data abstraction, or abstract data types, is a programming methodology where one defines not only the data structure to be used, but.
1 Nested and Inner classes Reading for these lectures: Weiss, Section 15.1 (Iterators and nested classes), Section 15.2 (Iterators and inner classes).
CSE 143 Lecture 22: Advanced List Implementation (ADTs; interfaces; abstract classes; inner classes; generics; iterators)
COMP171 Data Structure & Algorithm Tutorial 1 TA: M.Y.Chan.
Loops – While, Do, For Repetition Statements Introduction to Arrays
Building Java Programs Inner classes, generics, abstract classes reading: 9.6, 15.4,
CS 2511 Fall  Abstraction Abstract class Interfaces  Encapsulation Access Specifiers Data Hiding  Inheritance  Polymorphism.
1 Implementing a queue in an array Hashing We show a neat idea that allows a queue to be stored in an array but takes constant time for both adding and.
OOP in Java – Inner Classes Nelson Padua-Perez William Pugh Department of Computer Science University of Maryland, College Park.
Interfaces and Inner Classes. What is an Interface?  What is “presented to the user”?  The public part of a class?  What is the substance of an interface?
Iterators CS 367 – Introduction to Data Structures.
Iterator COMP 401, Spring 2013 Lecture 07 1/31/2013.
CS2110 Recitation 07. Interfaces Iterator and Iterable. Nested, Inner, and static classes We work often with a class C (say) that implements a bag: unordered.
Programming Languages and Paradigms Object-Oriented Programming.
Chapter 3 Introduction to Collections – Stacks Modified
Advanced Java Session 3 New York University School of Continuing and Professional Studies.
1 Lecture 09 Iterators and Enumerations Reading for these lectures: Weiss, Section Iterator Interface. Much better is: ProgramLive, Section 12.3.
CSC 212 Object-Oriented Programming and Java Part 1.
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.
Mason Vail.  A data type definition – “blueprint for objects”  Includes properties and/or methods ◦ “instance” data / methods – specific to one object.
Features of Object Oriented Programming Lec.4. ABSTRACTION AND ENCAPSULATION Computer programs can be very complex, perhaps the most complicated artifact.
An Introduction to Java Chapter 11 Object-Oriented Application Development: Part I.
Jan 12, 2012 Introduction to Collections. 2 Collections A collection is a structured group of objects Java 1.2 introduced the Collections Framework Collections.
CMSC 202 Generics. Nov Generalized Code One goal of OOP is to provide the ability to write reusable, generalized code. Polymorphic code using.
CSCI-383 Object-Oriented Programming & Design Lecture 13.
EECE 310: Software Engineering Iteration Abstraction.
Array Processing - 2. Objectives Demonstrate a swap. Demonstrate a linear search of an unsorted array Demonstrate how to search an array for a high value.
Object Based Programming Chapter 8. 2 In This Chapter We will learn about classes Garbage Collection Data Abstraction and encapsulation.
Generic Programming  Object Type  Autoboxing  Bag of Objects  JCL Collections  Nodes of Objects  Iterators.
Data Structure Introduction.
Introduction to Java Lecture Notes 3. Variables l A variable is a name for a location in memory used to hold a value. In Java data declaration is identical.
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
CSE 143 Lecture 24 Advanced collection classes (ADTs; abstract classes; inner classes; generics; iterators) read 11.1, 9.6, , slides.
CSCI 1100/1202 April 1-3, Program Development The creation of software involves four basic activities: –establishing the requirements –creating.
This recitation 1 An interesting point about A3: Using previous methods to avoid work in programming and debugging. How much time did you spend writing.
Final Review. From ArrayLists to Arrays The ArrayList : used to organize a list of objects –It is a class in the Java API –the ArrayList class uses an.
Design Patterns Software Engineering CS 561. Last Time Introduced design patterns Abstraction-Occurrence General Hierarchy Player-Role.
An Advanced Code Pattern: Inner Classes CSE301 University of Sunderland Harry R. Erwin, PhD Half Lecture.
Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class.
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
Nested Classes CompSci 230 S Software Construction.
Programmeren 1 6 september 2010 HOORCOLLEGE 2: INTERACTIE EN CONDITIES PROGRAMMEREN 1 6 SEPTEMBER 2009 Software Systems - Programming - Week.
Iterators, Iterator, and Iterable 2015-T2 Lecture 8 School of Engineering and Computer Science, Victoria University of Wellington COMP 103 Thomas Kuehne.
Lecture 8: Advanced OOP Part 2. Overview Review of Subtypes Interfaces Packages Sorting.
Access Specifier. Anything declared public can be accessed from anywhere. Anything declared private cannot be seen outside of its class. When a member.
Iteration Abstraction SWE Software Construction Fall 2009.
Chapter 4: More Object Concepts. Objectives Understand blocks and scope Overload a method Avoid ambiguity Create and call constructors with parameters.
Swing Threading Nested Classes COMP 401 Fall 2014 Lecture 23 11/25/2014.
SourceAnatomy1 Java Source Anatomy Barb Ericson Georgia Institute of Technology July 2008.
Basic Syntax อ. ยืนยง กันทะเนตร คณะเทคโนโลยีสารสนเทศและการสื่อสาร มหาวิทยาลัยพะเยา Chapter 2.
Collections Dwight Deugo Nesa Matic
CSE 501N Fall ‘09 10: Introduction to Collections and Linked Lists 29 September 2009 Nick Leidenfrost.
CS 116 OBJECT ORIENTED PROGRAMMING II LECTURE 4 GEORGE KOUTSOGIANNAKIS Copyright: 2016 Illinois Institute of Technology/George Koutsogiannakis 1.
CPSC 252 ADTs and C++ Classes Page 1 Abstract data types (ADTs) An abstract data type is a user-defined data type that has: private data hidden inside.
David Evans CS201J: Engineering Software University of Virginia Computer Science Lecture 5: Implementing Data Abstractions.
Part 1: Composition, Aggregation, and Delegation Part 2: Iterator COMP 401 Fall 2014 Lecture 10 9/18/2014.
Chapter 5 – Part 3 Conditionals and Loops. © 2004 Pearson Addison-Wesley. All rights reserved2/19 Outline The if Statement and Conditions Other Conditional.
1 Classes and Data Abstraction Chapter What a Class ! ! Specification and implementation Private and public elements Declaring classes data and.
Building Java Programs Generics, hashing reading: 18.1.
Geoff Holmes and Bernhard Pfahringer COMP206-08S General Programming 2.
Object Based Programming Chapter 8. 2 Contrast ____________________ Languages –Action oriented –Concentrate on writing ________________ –Data supports.
1 Iterators & the Collection Classes. 2 » The Collection Framework classes provided in the JAVA API(Application Programmer Interface) contains many type.
EECE 310: Software Engineering
Lecture 15: More Iterators
Object-Oriented Programming & Design Lecture 14 Martin van Bommel
Software Design Lecture : 39.
CSG2H3 Object Oriented Programming
Presentation transcript:

Generic Programming and Inner classes ge·ner·ic 1a : relating or applied to or descriptive of all members of a genus, species, class, or group : common to or characteristic of a whole group or class : typifying or subsuming : not specific or individual. Reading: Weiss: (Section 4.6) ProgramLive: Sections 12.3 and A use of generic: We like to buy generic drugs, instead of brand-name drugs, because they are cheaper. poly·mor·phism: the quality or state of being polymorphous: as (1) : capability of assuming different forms : capability of wide variation

1 // = “v is in b” static boolean linearSearch (int b, int v) { for (int k= 0; k < b.length; k= k+1) if (b[k] == v) return true; return false; } Recall linear search code Code in red relies on data being stored in a 1-D array of ints. For-loop also implicitly assumes that data is stored in 1-D array. Does not work for other types or if data is stored in a more general data structure such as a 2-D array.

2 // = “v is in b” static boolean linearSearch (Comparable[] b, Object v) { for (int k= 0; k < a.length; k= k+1) if (a[i].compareTo(v) == 0) return true; return false; } This linear search code not dependent on types More generic, because it is independent of the type of the array. This is polymorphism. But: still relies on data being stored in a 1-D array. This code will not work if data is stored in a more general data structure such as a 2-D array.

3 Goal First version of linear search –Input was array of int More generic version of linear search –Input was array of Comparable Can we write a still more generic version of linear search that is independent of data structure? –For example, work even with 2-D arrays of Comparable

4 Key ideas in solution Iterator interface Linear search written once and for all using Iterator interface Data class that wants to support linear search must implement Iterator interface Implementing Iterator interface –Inner classes provide elegant solution

5 Rewrite linear search using while-loop // = “v is in b” static boolean linearSearch (Comparable[] a, Object v) { int k= 0; // invariant: v is not in a[0..k-1] while (k < a.length) { if (a[k].compareTo(v) == 0) return true; k= k+1; } return false; } Intuitively, linear search needs to know - are there more elements to look at? - if so, get me the next element

6 Intuitive idea of generic linear search Data is contained in some object. Object has an adapter that permits data to be enumerated in some order. Adapter has two buttons –boolean hasNext(): are there more elements to be enumerated? –Object Next(): if so, give me a new element that has not been enumerated so far Linear search

7 Iterator interface public interface Iterator { boolean hasNext(); Object next(); void remove(); //we will not use this } This interface is predefined in package java.util. Linear search is written using this interface. Data class must provide an implementation of this interface.

8 Generic Linear Search static boolean linearSearch(Iterator b, Object v) { while (b.hasNext()) if (((Comparable) b.next()).compareTo(v) == 0) return true; return false; } static boolean linearSearch(Comparable[] k, Object v){ int k= 0; while (k < a.length) { if (a[k].compareTo(v) == 0) return true; k= k+1; } return false; } array version Iterator version

9 How does data class implement Iterator interface? Let us look at a number of solutions. 1.Adapter code is part of class containing data 2.Adapter is a separate class that is hooked up to data class 3.Adapter is an inner class in class containing data

10 Adapter (version 1) public class Crock1 implements Iterator{ private SomeClass[] a; //Class SomeClass must implement // Comparable private int cursor= 0; //index of next element to be enumerated /** Constructor: an instance with … public Crock1() { …store data in array a… } public boolean hasNext() { return (cursor < a.length); } public Object next() { cursor= cursor + 1; return a[cursor-1]; } public void remove() {}//unimplementated }

11 Critique As shown, client class can enumerate elements only once! –How do we reset the cursor? Making the data class implement Iterator directly is something of a crock because its concern should be with data, rather than enumeration of data.

12 One solution to resetting the cursor: –Data class implement a method void reset() which resets all internal cursor(s) –Method must be declared in Iterator interface But we still cannot have multiple enumerations of elements going on at the same time Remember: only one cursor…. Problem: cannot create new cursors on demand To solve this problem, cursor must be part of a different class that can be instantiated any number of times for a single data object.

13 Sharks and remoras Data class is like shark Iterator implementation is like a remora. Single shark must allow us to hook many remoras to it.

14 Adapter (version 2) class Shark{ public Comparable[] a; // Constructor: … public Shark() {…get data into a…} … } Remora teeth public class Remora implements Iterator{ int cursor; Shark myShark; public Remora(Shark s) { { myShark= s; cursor= 0; } public boolean hasNext() { return (cursor < myShark.a.length); } public Object next() { cursor= cursor+1; return myShark.a[cursor-1];} public void remove() {} //unimplemented } The client, using Shark: Shark s= new Shark(…); … Iterator enum= new Remora(s); while (enum.hasNext()) { … }

15 ….. Shark s = new Shark(); //object containing data Iterator enum= new Remora(s)…. Object v = ….; boolean b = linearSearch( new Remora(s), v); ….. Client code: myShark = cursor = 0 Shark Remora

16 Critique Good: –Class Shark focuses on data, class Remora focuses on enumeration Bad: –Remora code relies on being able to access Shark variables such as array a What if a is declared private (which we want)? –Remora is specialized to Shark but code appears outside Shark class 2-D array Shark will require a different Remora We may change class Shark and forget to update Remora.

17 Solution: use an inner class A class can be defined in several places: By itself As a component of a class just like a field or method Within a method just like a local variable Expression-level Inner class defined as it were part of an expression Called anonymous classes We focus on a class as a component of a class.

18 Adapter (version 2) class Shark{ public Comparable[] a; // Constructor: … public Shark() {…get data into a…} … } Remora teeth public class Remora implements Iterator{ int cursor; Shark myShark; public Remora(Shark s) { myShark= s; cursor= 0; } public boolean hasNext() { return (cursor < myShark.a.length); } public Object next() { cursor= cursor+1; return myShark.a[cursor-1];} public void remove() {} //unimplemented } Shark s= new Shark(…); … Iterator enum= new Remora(s); while (enum.hasNext()) { … }

19 Adapter (version 3) class Shark{ private Comparable[] a; // Constructor: … public Shark() {…get data into a…} … private class Remora implements Iterator{ int cursor; Shark myShark; public Remora(Shark s) { myShark= s; cursor= 0; } public boolean hasNext() { return (cursor < myShark.a.length); } public Object next() { cursor= cursor+1; return myShark.a[cursor-1]; } public void remove() {} //unimpl. } // end Remora // = an iterator over the data of this Shark public Iterator getSharkIterator() { return new Remora(); } } // end Shark

20 Important Points Instances of inner class have access to all components of containing outer class instance Inner class can be declared to be public, private, or protected –Inner class name is visible accordingly We choose to make the inner class private and to provide a public method that returns an instance of the inner class.

21 Client code … Shark s = new Shark(); //object containing data // manipulate the data in Shark s Object v = ….; // Set b to “v is somewhere in the data of s” boolean b = linearSearch(s. getSharkIterator (), v); …..

22 Website In the lecture notes page, where we list lectures: for lecture 10, a file innerclass.zip, which contains: 1.List211. Our interface for lists) 2.Stack2. Our implementation of a stack in an array, with an inner class that is an Iterator over the stack elements. 3.Generics. Methods for doing a linear search of an Iterator, finding the max of an Iterator, and finding the min of an Iterator. We urge you to download this program and study it!!! Load it into DrJava and do calls on it in the Interactions pane.