1 Interfaces and related issues Reading for these lectures: Weiss, Section 4.4 (The interface), p. 110. no multiple inheritance with classes public class.

Slides:



Advertisements
Similar presentations
Programming Paradigms Introduction. 6/15/2005 Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved. L1:
Advertisements

SUMMARY: abstract classes and interfaces 1 Make a class abstract so instances of it cannot be created. Make a method abstract so it must be overridden.
Java Review Interface, Casting, Generics, Iterator.
Exceptions and Exception Handling Carl Alphonce CSE116 March 9, 2007.
Generic programming in Java
Inheritance Inheritance Reserved word protected Reserved word super
1 Nested and Inner classes Reading for these lectures: Weiss, Section 15.1 (Iterators and nested classes), Section 15.2 (Iterators and inner classes).
Bag implementation Add(T item) – Enlarge bag if necessary; allocate larger array Remove(T item) – Reduce bag if necessary; allocate smaller array Iterator.
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.
ISBN Chapter 11 Abstract Data Types and Encapsulation Concepts.
1 Review of classes and subclasses M fast through this material, since by now all have seen it in CS100 or the Java bootcamp First packages Then classes.
1 Executing Method Calls This lecture tells you precisely how method calls are executed (a few details will have to wait until we get to classes and objects).
Aalborg Media Lab 23-Jun-15 Inheritance Lecture 10 Chapter 8.
CHAPTER 6 Stacks Array Implementation. 2 Stacks A stack is a linear collection whose elements are added and removed from one end The last element to be.
Chapter 10 Classes Continued
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?
1 Inner classes Reading for these lectures: Weiss, Section 15.1 (Iterators and nested classes), Section 15.2 (Iterators and inner classes). A nested class.
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.
COMP 103 Iterators and Iterable. RECAP  Maps and Queues TODAY  Queue Methods  Iterator and Iterable 2 RECAP-TODAY.
MIT AITI 2002 Abstract Classes, Interfaces. Abstract Classes What is an abstract class? An abstract class is a class in which one or more methods is declared,
Abstract Data Types (ADTs) and data structures: terminology and definitions A type is a collection of values. For example, the boolean type consists of.
1 Lecture 07 Interfaces and related issues Reading for these lectures: Weiss, Section 4.4 (The interface), p ProgramLive, Section 12.1 In User Interface.
1 Review of Java Higher Level Language Concepts –Names and Reserved Words –Expressions and Precedence of Operators –Flow of Control – Selection –Flow of.
Topic 3 The Stack ADT.
1 Lecture 09 Iterators and Enumerations Reading for these lectures: Weiss, Section Iterator Interface. Much better is: ProgramLive, Section 12.3.
1 Abstraction  Identify important aspects and ignore the details  Permeates software development programming languages are abstractions built on hardware.
Polymorphism, Inheritance Pt. 1 COMP 401, Fall 2014 Lecture 7 9/9/2014.
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.
2000 Jordan Anastasiade. All rights reserved. 1 Class In this lesson you will be learning about: Class. Inheritance. Polymorphism. Nested and.
EECE 310: Software Engineering Iteration Abstraction.
APCS Java AB 2004 Review of CS1 and CS2 Review for AP test #1 Sources: 2003 Workshop notes from Chris Nevison (Colgate University) AP Study Guide to go.
Arrays An array is a data structure that consists of an ordered collection of similar items (where “similar items” means items of the same type.) An array.
Inheritance - Polymorphism ITI 1121 Nour El Kadri.
Chapter 18 Java Collections Framework
RIT Computer Science Dept. Goals l Inheritance l Modifiers: private, public, protected l Polymorphism.
1 Interfaces Reading for today: Sec and corresponding ProgramLive material. Also, compare with previous discussions of abstract classes (Sec. 4.7).
Chapter 3 Inheritance and Polymorphism Goals: 1.Superclasses and subclasses 2.Inheritance Hierarchy 3.Polymorphism 4.Type Compatibility 5.Abstract Classes.
Comparison-Based Sorting & Analysis Smt Genap
Programming in Java CSCI-2220 Object Oriented Programming.
Object Oriented Software Development
CSE 143 Lecture 24 Advanced collection classes (ADTs; abstract classes; inner classes; generics; iterators) read 11.1, 9.6, , slides.
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.
90-723: Data Structures and Algorithms for Information Processing Copyright © 1999, Carnegie Mellon. All Rights Reserved. 1 Lecture 1: Introduction Data.
U n i v e r s i t y o f H a i l 1 ICS 202  2011 spring  Data Structures and Algorithms 
Chapter 6 Object-Oriented Design Part 2. © 2004 Pearson Addison-Wesley. All rights reserved2/20 The this Reference The this reference allows an object.
Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class.
1 Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L 9.1 – 9.4.
Interfaces F What is an Interface? F Creating an Interface F Implementing an Interface F What is Marker Interface?
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.
Lecture 7 February 24, Javadoc version and author Tags These go in the comments before named classes. –Put your SS# on a separate line from the.
Lecture 8: Advanced OOP Part 2. Overview Review of Subtypes Interfaces Packages Sorting.
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
Interfaces. In order to work with a class, you need to understand the public methods  methods, return types,…  after you instantiate, what can you do.
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
Chapter 9: Continuing Classes By Matt Hirsch. Table Of Contents 1.Static Fields and Methods 2.Inheritance I. Recycle Code with Inheritance II. Overriding.
1 Stacks Abstract Data Types (ADTs) Stacks Application to the analysis of a time series Java implementation of a stack Interfaces and exceptions.
CSE 332: C++ Exceptions Motivation for C++ Exceptions Void Number:: operator/= (const double denom) { if (denom == 0.0) { // what to do here? } m_value.
Programming in Java: lecture 7
EECE 310: Software Engineering
7.1 What Is An Object Object-oriented program - Description or simulation of application Object-oriented programming is done by adopting or extending an.
Java Programming Language
Lecture 26: Advanced List Implementation
Abstract Class As per dictionary, abstraction is the quality of dealing with ideas rather than events. For example, when you consider the case of ,
Lecture 16 - Interfaces Professor Adams.
Java Programming Language
CSE 143 Lecture 21 Advanced List Implementation
Corresponds with Chapter 5
Presentation transcript:

1 Interfaces and related issues Reading for these lectures: Weiss, Section 4.4 (The interface), p no multiple inheritance with classes public class Student { public class Employee {…} public class StudentEmployee extends Student, Employee { … } Such multiple inheritance has been tried in several languages, but it never works correctly. Trouble with ambiguity. E.g. what if method getName is defined in both superclasses but they yield different values? No good theory of such multiple inheritance has been developed yet, so Java does not allow it. not allowed. doesn’t work.

2 !!Interrupt!!! Don’t override variables. Don’t do this: public class C { public int x; } public class Sub extends C { public int x; } (Actually called shadowing the variable.) Overriding methods is useful. We know of know compelling case where overriding a variable helps. Our rules for executing method calls do not take into account overriding variables. Forget completely about overriding variables, and never do it.

3 An interface contains the result types (or void) and signatures of some methods. The methods are called “abstract” because their bodies are not present; the bodies are replaced by semi- colons. The methods are automatically public. public interface Comparable { // = if this Object < ob then a negative integer // if this Object = ob, then 0 // if this Object > ob, then a positive integer int compareTo (Object ob); } The signature of a method consists of its name and its parameter declarations (enclosed in parentheses and separated by commas). The interface abstract method: body replaced by “;” no prefix (static, public, etc.)

4 public interface Comparable { // = if this Object < ob then a negative integer // if this Object = ob, then 0 // if this Object > ob, then a positive integer int compareTo (Object ob); } The “implements clause” in the class definition indicates that the class defines all the methods of the named interface. It’s a syntactic error not to do so; the program won’t compile. public class Shape implements Comparable { … int compareTo(Ob ob) { body of method compareTo } Implementing an interface implements clause definition of compareTo

5 public class Shape implements Comparable { … // = if this Object < ob then a negative integer // if this Object = ob, then 0 // if this Object > ob, then a positive integer // (it’s expected that ob is really a Shape) int compareTo(Object ob) { if (this.area() < ((Shape)ob).area()) return -1; if (this.area() == ((Shape)ob).area()) return 0; return 1; } (in this case, Shapes are ordered by their area) Implementing method compareTo In this case, the parameter of compareTo is expected to be an instance of Shape, because the method is defined in Shape ob is cast to Shape

6 public class ArrayMethods { // = index of the max value in nonempty b public static int max(Comparable[] b) { int j= 0; // {invariant: b[j] is the max of b[0..i-1]} for (int i= 1; i != b.length; i= i+1) { if (b[i].compareTo(b[j]) > 0) j= i; } return j; } Shape[] s= new Shape[20]; Integer[] x= new Integer[100]; Fill s and x with values. int maxs= ArrayMethods.max(s); int maxx= ArrayMethods.max(x); Why is the interface concept useful? max will find the max of any array b whose base class implements Comparable! In Java 2, version 1.3.1, all primitive-type wrapper classes except Boolean implement Comparable.

7 public class ArrayMethods { // = index of the max value in nonempty b public static int max(Comparable[] b) { int j= 0; // {invariant: b[j] is the max of b[0..i-1]} for (int i= 1; i != b.length; i= i+1) { if (b[i].compareTo(b[j]) > 0) j= i; } return j; } Shape[] s= new Shape[20]; Fill s with values. int maxs= ArrayMethods.max((Comparable[]) s); int maxs= ArrayMethods.max(s); An interface acts like a type, and casts to and from an interface are allowed! unnecessary cast because it widens

8 public class Shape implements Comparable { … } public class Parallelogram extends Shape implements Comparable, Comp2 { … } public interface Comparable { … } public interface In1 { … } public interface Comp2 extends In1 {… } Class and interface hierarchies Object Shape Parallelogram An interface, like a class, is handled like a type: can cast to and from an interface.

9 public class Shape implements Comparable { … } public class Parallelogram extends Shape implements Comparable, Comp2 { … } public interface Comparable { … } public interface In1 { … } public interface Comp2 extends In1 {… } Class and interface hierarchies Object Shape Parallelogram Comparable Comp2 In1 Upward cast: widening; done automatically when necessary Downward cast: narrowing; not automatic

10 Parallelogram p= new Parallelogram(); legal Shape s= (Shape) p;legal (Comparable) plegal (Comparable) slegal (Comp2) plegal (Comp2) sillegal (In1) p legal (In1) sillegal ((In1)p).equals(…) legal In1 I= (In1) p; Using In1, can reference only names accessible in In1. Class and interface hierarchies Object Shape Parallelogram Comparable Comp2 In1 Note that Object acts like a super interface Object

11 public class Arrays { public static int max(Comparable[] b) { int j= 0; // {invariant: b[j] is the max of b[0..i-1]} for (int i= 1; i != b.length; i= i+1) { if (b[i].compareTo(b[j]) > 0) j= i; } return j; } public class Shape implements Comparable { int compareTo(Object ob) { Shape x= (Shape)ob; if (this.area() < x.area()) return -1; if (this.area() == x.area()) return 0; return 1; } public class M { public static void main(…) { Shape[] s= new Shape[20]; Fill s with values. int m= Arrays.max(s); L1: } **

12 main pars M in system m s a a0 a1 a2 … a20 Shape[] Arrays L1 max b a0 Comparable[] j 0 i 1 a1 Shape area compareTo a2 Shape area compareTo Shape a2 ** ob a1 Object[] x a1 Shape [] This slide shows the call stack for the call Arrays.max(s); on the previous slide, just after execution of Shape x= (Shape)ob; in method a2.compareTo.

13 Functors (function objects) Interface Comparable doesn’t fit all situations. For an array of integers, there are several ways to sort it -- ascending order, descending order, in order of distance from 0 (e.g. 0,1,-1, 2, -2, 3, -4, …), etc. We want to use the same sort method to sort the array in any order. Solution: pass a comparison function to method sort: // Sort array b using sort method f public static void sort(int[] b, function f) { … if f(b[i],b[j])... } public static void main(String[] pars) { int[] x= new int[50]; Fill array x with values; sort(x, greaterequal); sort(x, lessequal); } // = “x <= y” public static boolean lessequal(int x, int y) {return x <= y;} // = “x >= y” public static boolean greaterequal(int x, int y) {return x >= y;} illegal in Java!

14 Functors (function objects) A function cannot be an argument, but an instance of a class that is guaranteed to contain a function can! // A functor with boolean function compare(x,y) public interface CompareInterface { // = x <= y boolean compare(Object x, Object y); } // Sort array b using functor c public static void sort(int[] b, CompareInterface c) { … if c.compare(b[i],b[j])... } An instance of interface is a functor: an instance with exactly one function defined it it. parameter c is guaranteed to contain function compare

15 Consequence of using a functor One sort method can be used to sort an array of any base class; you provide the functor that does the comparing. // A functor with boolean function compare(x,y) public interface CompareInterface { // = x compared to y boolean compare(Object x, Object y); } public class Less implements CompareInterface { // = “x < y” public boolean compare(Object x, Object y) {return ((Integer )x).intValue() < ((Integer )y).intValue();} } public class Greater implements CompareInterface { // = “x > y” public boolean compare(Object x, Object y) {return ((Integer )x).intValue() > ((Integer )y).intValue();} } // Sort array b using functor c public static void sort(int[] b, CompareInterface c) { … if c.compare(b[i],b[j])... }

16 Consequence of using a functor // A functor with boolean function compare(x,y) public interface CompareInterface { // = x compared to y boolean compare(Object x, Object y); } public class Less implements CompareInterface { // = “x < y” public boolean compare(Object x, Object y) {return …; } } public class Greater implements CompareInterface { // = “x > y” public boolean compare(Object x, Object y) {return …; } } // Sort array b using functor c public static void sort(int[] b, CompareInterface c) { … if c.compare(b[i],b[j])... } public static void main(String[] pars) { int[] x= new int[50]; Fill array x with values; sort(x, new Less()); sort(x, new Greater()); }

17 Nested classes Using functors as we have been doing tends to lead to a proliferation of classes (and files that contain them), like Less, and Greater, which may be used only once: public static void main(String[] pars) { int[] x= new int[50]; Fill array x with values; sort(x, new Less()); } public class Less implements CompareInterface { // = “x < y” public boolean compare(Object x, Object y) {return …; } } Nested classes, as illustrated on the next slide remove the need for so many files. may be only creation of instance of Less in the whole program!

18 Nested classes public class MainClass { public static void main(String[] pars) { int[] x= new int[50]; Fill array x with values; sort(x, new Less()); } private static class Less implements CompareInterface { // = “x < y” public boolean compare(Object x, Object y) {return …; } } Less, defined using static, is called a nested class. It is nested inside class MainClass. It could have any visibility modifier; it need not be private. Because Less is declared within MainClass, it is a static component of MainClass, and it can reference any other static components. A component like Less is called a nested class ONLY if it is static.

19 Anonymous classes Even the use of a nested class forces us to name a class that may be used only once. There is a way to write a class that is going to be used only once, without giving it a name --it’s an anonymous class. Here’s an example: new CompareInterface() { // = “x <= y” public boolean compare(Object x, Object y) { return ((Integer )x).intValue() <= ((Integer )y).intValue(); } public class Less implements CompareInterface { // = “x < y” public boolean compare(Object x, Object y) {return …; } } name of an interface definition of the methods of the interface --looks just like the body of class Less

20 Use of an anonymous class public static void main(String[] pars) { int[] x= new int[50]; Fill array x with values; sort(x, new CompareInterface() { // = “x <= y” public boolean compare(Object x, Object y) { return ((Integer )x).intValue() <= ((Integer )y).intValue(); } ); } Use interface name as the name of a class. Put in body the desired implementation of function compare. public class Less implements CompareInterface { // = “x < y” public boolean compare(Object x, Object y) {return …; } } create instance of the anonymous class no longer needed

21 Iterators Reading: Weiss, Sect 6.1, Sect 6.2, the Iterator pattern, Sect 6.3.2, Interface Iterator We will see one way that Java features allow for the reuse of program components. Definition: A data structure: representation of data together with operations that manipulate the date.

22 Iterators Loop to process elements of an array: int j= 0; while (j != b.length) { Process b[j]; j= j+1; } Loop to process prime numbers less than 100: int j= 2; while (j < 100) { Process j; Set j to the next prime number } There is a pattern to process any sequence v. Write an interface for that pattern. while (there exists another item to process) { Get the next item; Process the item } Write an interface that can be used to implement classes for iterating over any sequence.

23 Interface java.util.Iterator (only in version 1.2 and 1.3) // An Iterator allows processing of items of a sequence public interface Iterator { // = “there is another item to process” public boolean hasNext(); // = the next item to process. Can be called only once // per item. Throws an exception if no more items exist public Object next() throws NoSuchElementException; // Remove the last element returned by the Iterator. // Throw an UnsupportedOperationException if not // implemented. // Throw an IllegalStateException if next has not yet // been called or remove was already called for the item public void remove() throws UnsupportedOperationException, IllegalStateException; } We won’t deal with method remove for the moment.

24 Interface java.util.Enumeration (in all versions 1.2 and 1.3) // An Enumerator allows processing of items of a sequence public interface Iterator { // = “there is another item to process” public boolean hasMoreElements(); // = the next item to process. Can be called only once // per item. Throws an exception if no more items exist public Object nextElements() throws NoSuchElementException; } Java would rather you use interface Iterator than Enumeration.

25 Example of use of interface Iteration import java.util.*; // An instance is an iterator over a prefix of the primes public class PrimeIterator implements Iterator{ int n; // produce primes less than n int p= 2; // the next prime to produce // Constructor: an instance for primes less than n public PrimeIterator(int n) { this.n= n; } // = there is another prime to process public boolean hasNext() { return p < n; } // = the next item to process. Can be called only once // per item. Throws an exception if no more items exist public Object next() throws NoSuchElementException { if ( p >= n) throw new NoSuchElementException(); int returnValue= p; p= p+1; while (!isPrime(p)) { p= p+1;} return new Integer(returnValue); } // Remove last element returned by Iterator. Unsupported public void remove() {throw …; } // = “p is a prime”. Precondition: p >= 2 public boolean isPrime(int p) { … } }

26 Example of use of class PrimeIterator import java.util.*; public class Example { public static void main(String[] pars) { PrimeIterator pi= new PrimeIterator(50); while (pi.hasNext()) { Integer i= (Integer)pi.Next(); System.out.println(i); } or public class Example { public static void main(String[] pars) { PrimeIterator pi= new PrimeIterator(50); while (pi.hasNext()) { System.out.println(pi); }

27 Example of use of class KeyboardIterator, which is given on next slides import java.util.*; public class Example { public static void main(String[] pars) { System.out.println("Type numbers into keyboard"); KeyboardIterator ki= new KeyboardIterator(); while (ki.hasNext()) { Integer i= (Integer)ki.next(); System.out.println("integer is: " + i); System.out.flush(); }

28 Class KeyboardIterator import java.io.*; import java.util.*; // Iterator for processing a seq of nonzero ints, one per line, // from keyboard (terminated by 0). Assume that keyboard // is not open at the time. The items are of class Integer. // hasNext should be called first, and calls to hasNext // and next should alternate public class KeyboardIterator implements Iterator{ BufferedReader br; // Link to keyboard int p; // The last integer read (1 if none) boolean toHasNext;// Next call should be to hasNext // (and not to next) // Constructor: an instance that reads from the keyboard public KeyboardIterator() { InputStreamReader isr= new InputStreamReader(System.in); br= new BufferedReader(isr); p= 1; toHasNext= true; }

29 Class KeyboardIterator (continued) // = there is another input integer to process public boolean hasNext() { if (!toHasNext) throw new RuntimeException("hasNext was called” + “ when next should have been called"); toHasNext= false; p= readInt(); if (p != 0) return true; try { br.close(); } catch (IOException ex) { System.out.println("IO error reading from keyboard"); System.exit(0); } return false; }

30 Class KeyboardIterator (continued) // = the next item to process, as an Integer. Call only // once per item. Throw exception if no more items exist public Object next() throws NoSuchElementException { if (toHasNext) throw new RuntimeException("hasNext called " + "when next should have been called"); if (p == 0) throw new RuntimeException("no more elements"); toHasNext= true; return new Integer(p); } // Not supported. Does nothing. public void remove() { } // Read and return the next integer from br (the keyboard) public int readInt() { As in recitation handout } }

31 Some uses of interfaces Functors. We are able to define a class that is guaranteed to define a certain function. Allows us, for example, to define a single sort procedure that will sort any array whose base class implements compareTo. Iterators. We are able to define a pattern that can be used to define classes for iterating over (or enumerating) any finite sequence of values --a range of integers, a range of prime numbers, the values of an array, the lines of a file, the integers typed on the keyboard, and so on. Later, we see how to define iterators over (or enumerators of) various “data structures”. Define “abstract datatypes”. A data type is a set of values together with a set of operations on them. Example: a stack, which is a list of values with three operations: push a value onto (the top of) the stack, pop the top element of the stack, and a test for emptiness. We can define such a datatype using an interator and then implement it in various ways. The assignment for this topic gives you practice in this.