Interfaces.

Slides:



Advertisements
Similar presentations
 Specifies a set of methods (i.e., method headings) that any class that implements that interface must have.  An interface is a type (but is not a class).
Advertisements

Mouse Listeners We continue our examination of GUIs by looking at how to interact with the mouse –Just as Java creates Events when the user interacts with.
© The McGraw-Hill Companies, 2006 Chapter 14 Abstraction, inheritance and interfaces.
Lecture 17 Abstract classes Interfaces The Comparable interface Event listeners All in chapter 10: please read it.
1 Inheritance. 2 One class inherits from another if it describes a specialized subset of objects Terminology: inheritschild class subclass –the class.
Event Handling Events and Listeners Timers and Animation.
Slides prepared by Rose Williams, Binghamton University Chapter 13 Interfaces and Inner Classes.
Interfaces. In this class, we will cover: What an interface is Why you would use an interface Creating an interface Using an interface Cloning an object.
Chapter 13 Interfaces and Inner Classes Slides prepared by Rose Williams, Binghamton University Copyright © 2008 Pearson Addison-Wesley. All rights reserved.
1 Chapter 6 Inheritance, Interfaces, and Abstract Classes.
Slides prepared by Rose Williams, Binghamton University Chapter 13 Interfaces and Inner Classes.
Aalborg Media Lab 28-Jun-15 Software Design Lecture 8 “Arrays”
Lecture 18 Review the difference between abstract classes and interfaces The Cloneable interface Shallow and deep copies The ActionListener interface,
CS102--Object Oriented Programming Lecture 15: Interfaces Copyright © 2008 Xiaoyan Li.
16-Aug-15 Air Force Institute of Technology Electrical and Computer Engineering Object-Oriented Programming in Java Topic : Interfaces, Copying/Cloning,
Java Implementation Software Construction Lecture 6.
CMSC 202 Interfaces. 11/20102 Classes and Methods When a class defines its methods as public, it describes how the class user interacts with the method.
Chapter 6 Class Inheritance F Superclasses and Subclasses F Keywords: super F Overriding methods F The Object Class F Modifiers: protected, final and abstract.
MT311 Java Application Development and Programming Languages Li Tak Sing( 李德成 )
220 FINAL TEST REVIEW SESSION Omar Abdelwahab. INHERITANCE AND POLYMORPHISM Suppose you have a class FunClass with public methods show, tell, and smile.
Chapter 11 Java AWT Part I: Mouse Events (Optional) Lecture Slides to Accompany An Introduction to Computer Science Using Java (2nd Edition) by S.N. Kamin,
Java Programming: Guided Learning with Early Objects
CS 11 java track: lecture 4 This week: arrays interfaces listener classes inner classes GUI callbacks.
1 1 Abstract Classes and Interfaces. 22 Motivations You learned how to write simple programs to display GUI components. Can you write the code to respond.
7/3/00SEM107- © Kamin & ReddyClass 11 - Events - 1 Class 11 - Events r A couple of odds & ends m Component sizes  switch statement r Event types r Catching.
Graphic User Interface. Graphic User Interface (GUI) Most of us interact with computers using GUIs. GUIs are visual representations of the actions you.
Java Interfaces. Interfaces An interface is something like an extreme case of an abstract class – However, an interface is not a class – It is a type.
Comp 249 Programming Methodology Chapter 13 Interfaces & Inner Classes Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.
MSc Workshop - © S. Kamin, U.Reddy Lect 4 - Events - 1 Lecture 4 – Event Handling r Painting r Event types r Catching different event types.
12/5/00SEM107, Kamin & ReddyReview - 34 Events Event types Catching different event types Getting information from components and events Distinguishing.
For (int i = 1; i
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Outline 21.1 Test-Driving the Painter Application.
Object Oriented Programming.  Interface  Event Handling.
Agenda Introduction. Event Model. Creating GUI Application. Event Examples.
Chapter 14 Abstract Classes and Interfaces. Abstract Classes An abstract class extracts common features and functionality of a family of objects An abstract.
CSC 1601 Exam 1 Review. Topics  javadoc  Advanced Java I/O  Objects  References  Static variables and methods  Wrapper classes  Class parameters.
Mouse Listeners Moving the mouse will also generate events like the Timer –To have your program respond, you must implement either or both of MouseListener.
Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
Interfaces and Inner Classes
Interfaces F What is an Interface? F Creating an Interface F Implementing an Interface F What is Marker Interface?
COM S 228 Introduction to Data Structures Instructor: Ying Cai Department of Computer Science Iowa State University Office: Atanasoff.
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
MT311 Java Application Development and Programming Languages Li Tak Sing ( 李德成 )
1 Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
Chapter 13 Interfaces and Inner Classes Slides prepared by Rose Williams, Binghamton University Copyright © 2008 Pearson Addison-Wesley. All rights reserved.
Slides prepared by Rose Williams, Binghamton University ICS201 Lecture 7 : Interfaces King Fahd University of Petroleum & Minerals College of Computer.
Java Programming: Guided Learning with Early Objects Chapter 9 Inheritance and Polymorphism.
Chapter 13 Abstract Classes and Interfaces
Chapter 13 Abstract Classes and Interfaces
Chapter 7: Cloning and RTTI
Web Design & Development Lecture 9
Methods Attributes Method Modifiers ‘static’
Multithreading in Java
Comp 249 Programming Methodology
Interfaces and Inner Classes
Computer Science II Exam 1 Review.
Lecture 4: Interface Design
CMSC 202 Interfaces.
Java Programming Language
Chapter 12 Abstract Classes and Interfaces
Web Design & Development Lecture 12
Interfaces and Inner Classes
CMSC 202 Interfaces.
Lecture 11 Objectives Learn what an exception is.
Chapter 14 Abstract Classes and Interfaces
Interfaces.
Chapter 8 Class Inheritance and Interfaces
Java Programming: From Problem Analysis to Program Design, 4e
CMSC 202 Interfaces.
Presentation transcript:

Interfaces

Interfaces Specifies a set of methods (i.e., method headings) that any class that implements that interface must have. An interface is a type (but is not a class). Interface can be parameter types. (Java’s way of approximating multiple inheritance.)

Interfaces Abstract or concrete classes may implement interfaces.

Interfaces To implement an interface, a concrete class must do: State “implements InterfaceName” or “implements InterfaceName1, …, InterfaceNamen” You must implement all of the method headings listed in the definition(s) of the interface(s).

Interfaces To implement an interface, an abstract class must do: State “implements InterfaceName” or “implements InterfaceName1, …, InterfaceNamen” You must either implement all of the method headings listed in the definition(s) of the interface(s), or you must define as abstract the method headings in the interface(s).

Interfaces and interfaces An interface B may extend an interface A and specify additional method headings. Any concrete class that implements the derived interface B must implement all of the methods in both interfaces A and B.

The Comparable interface

The Comparable interface See http://docs.oracle.com/javase/1.4.2/docs/api/java/lang/Comparable.html Used for sorting. If things can be compared, they can be sorted. One method: public int compareTo ( Object other ); -1 means that this comes before (is less than) other 0 means that this and other are equal +1 means that this comes after (is greater than) other

The Comparable interface “This interface imposes a total ordering on the objects of each class that implements it. This ordering is referred to as the class's natural ordering, and the class's compareTo method is referred to as its natural comparison method.”

Totally ordered set. from http://mathworld. wolfram A total order (or "totally ordered set," or "linearly ordered set") is a set plus a relation on the set (called a total order) that satisfies the conditions for a partial order plus an additional condition known as the comparability condition. A relation <= is a total order on a set S ("<= totally orders S") if the following properties hold. Reflexivity: a<=a for all a in S. Antisymmetry: a<=b and b<=a implies a=b. Transitivity: a<=b and b<=c implies a<=c. Comparability (trichotomy law): For any a,b in S, either a<=b or b<=a. The first three are the axioms of a partial order, while addition of the trichotomy law defines a total order.

Using the Comparable interface if (a.compareTo(b) < 0) { … } else if (a.compareTo(b) == 0) { } else { //must be a.compareTo(b)>0 }

Double and String implement Comparable See http://docs.oracle.com/javase/6/docs/api/java/lang/Double.html. See http://docs.oracle.com/javase/6/docs/api/java/lang/String.html.

Problem Is the following a suitable implementation of the Comparable interface? public class Double2 implements Comparable { private double value; public Double2 ( double theValue ) { value = theValue; } public int compareTo ( Object other ) { return -1; public double getValue ( ) { return value; You can think of the underlying “comes-before” relationship as saying that for any objects d1 and d2, d1 comes-before d2.

Problem Is the following a suitable implementation of the Comparable interface? public class Double2 implements Comparable { private double value; public Double2 ( double theValue ) { value = theValue; } public int compareTo ( Object other ) { return -1; public double getValue ( ) { return value; You can think of the underlying “comes before” relationship as saying that for any objects d1 and d2, d1 comes before d2. Problems: 1. compareTo indicates that a<a. This is not true. When a==a, it should return 0. 2. When this is a and other is b, compareTo indicates a<b. But when this is b and other is a, compareTo indicates b<a. It cannot be both!

Problem Suppose you have a class Circle that represents circles all of whose centers are at the same point. (To make it concrete you can take the circles to be in the usual x,y plane and all have their centers at the origin.) Suppose there is a boolean valued method inside of the class Circle such that, for circles c1 and c2, c1.inside(c2) returns true if c1 is completely inside of c2 (and c2 is not the same as c1). Is the following a total ordering? c1 comes before c2 if c1 is inside of c2 (that is, c1.inside(c2) returns true). (You could represent objects of the class Circle by a single value of type double that gives the radius of the circle, but the answer does not depend on such details.)

Problem Suppose you have a class Circle that represents circles all of whose centers are at the same point. (To make it concrete you can take the circles to be in the usual x,y plane and all have their centers at the origin.) Suppose there is a boolean valued method inside of the class Circle such that, for circles c1 and c2, c1.inside(c2) returns true if c1 is completely inside of c2 (and c2 is not the same as c1). Is the following a total ordering? c1 comes before c2 if c1 is inside of c2 (that is, c1.inside(c2) returns true). (You could represent objects of the class Circle by a single value of type double that gives the radius of the circle, but the answer does not depend on such details.) Problem: not reflexive Reflexivity: a<=a for all a in S.

Constants and interfaces

Constants and interfaces Constants may be defined in interfaces but ... not really in the spirit of an interface must be public static final (and will be, even if omitted!) Also, no instance variables in interfaces.

Inconsistent interfaces

Inconsistent interfaces Let’s mplement two interfaces which: have conflicting constants, or have overloaded methods with different return types

Inconsistent interfaces Let’s implement two interfaces which have conflicting constants. class TestInterface implements I1, I2 { public static void main ( String[] args ) { System.out.println( A ); } interface I1 { int A = 100; interface I2 { int A = 500; Compiler error – ambiguous.

Inconsistent interfaces Let’s implement two interfaces which have overloaded methods with different return types. class TestInterface implements I1, I2 { public static void main ( String[] args ) { } public int f ( ) { return 0; interface I1 { public int f ( ); interface I2 { public String f ( ); Compiler error – TestInterface is not abstract and does not override abstract method f() in I2

Inconsistent interfaces Let’s implement two interfaces which have overloaded methods with different return types. class TestInterface implements I1, I2 { public static void main ( String[] args ) { } public int f ( ) { return 0; } public String f ( ) { return null; } interface I1 { public int f ( ); interface I2 { public String f ( ); Compiler error – f() is already defined in TestInterface

Consistent interfaces Let’s implement two interfaces which have overloaded methods with same return types. class TestInterface implements I1, I2 { public static void main ( String[] args ) { } public int f ( ) { return 0; interface I1 { public int f ( ); interface I2 { OK

The clone() method

Back to the Object class Note that the Object class has a clone() method. See http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Object.html. protected Object clone ( ) Creates and returns a copy of this object. Note that it’s protected. Interesting! Let’s give it a try.

clone() method public class Test { private int x=5; public static void main ( String args[] ) { Test t1 = new Test(); t1.x = 12; Test t2 = (Test)t1.clone(); System.out.println( t2.x ); } Compiler error: Test.java:8: unreported exception java.lang.CloneNotSupportedException; must be caught or declared to be thrown Test t2 = (Test)t1.clone(); ^ 1 error We discover that the clone method throws an exception (that we aren’t/forgot to handle).

clone() method public class Test { private int x=5; public static void main ( String args[] ) { Test t1 = new Test(); t1.x = 12; Test t2 = null; try { t2 = (Test)t1.clone(); } catch (Exception e) { System.out.println( "error: " + e ); } System.out.println( t2.x ); Compiles OK (we handle the exception). But get a runtime error: error: java.lang.CloneNotSupportedException: Test Exception in thread "main" java.lang.NullPointerException at Test.main(Test.java:14) Now we discover that Object’s clone seems to always thrown an exception no matter what we do. (As we will see, it’s because we failed to implement the Cloneable interface – which Object’s clone method checks!)

Cloneable interface has no headings has no constants So what does it do? Magic! Actually, implementing the Cloneable interface allows us to pass Object’s check.

clone() method revisited public class Test implements Cloneable { private int x=5; public static void main ( String args[] ) { Test t1 = new Test(); t1.x = 12; Test t2 = null; try { t2 = (Test)t1.clone(); } catch (Exception e) { System.out.println( "error: " + e ); } System.out.println( t2.x ); Compile OK. Runs OK. Outputs: 12

Cloneable interface Object.clone() exact, bit-by-bit copy may cause privacy leaks! To avoid privacy leaks, your clone() method should: Invoke super.clone(), and Create new instances of mutable types

Cloneable interface Simplest case You have no mutable instance variables (but you may have primitive and/or immutable instance variables), and You are derived from Object.

Cloneable interface: simplest case public class Test implements Cloneable { private int x=5; public Object clone ( ) { try { return super.clone(); } catch (Exception e) { return null; } public static void main ( String args[] ) { Test t1 = new Test(); t1.x = 12; Test t2 = (Test)t1.clone(); System.out.println( t2.x ); //outputs 12 Compiles OK. Runs w/out error/exception. We don’t have to trouble ourselves in main() with exceptions. Outputs 12 as expected.

Cloneable interface – more extensive case (w/ problem) import java.util.Date; import java.awt.Point; public class Point3D extends Point implements Cloneable { private int z = 0; private Date date = new Date(); public Object clone ( ) { Point3D copy = null; try { copy = (Point3D)super.clone(); } catch (Exception e) { return null; } return copy; public static void main ( String args[] ) { Point3D p1 = new Point3D(); Point3D p2 = (Point3D)p1.clone(); System.out.println( p2.date ); //month becomes March p1.date.setMonth( 2 ); } This example: Clones p1 into p2. Prints p2. Changes p1’s date. Prints p2 again (which has now magically changed).

Cloneable interface – more extensive case (problem fixed) import java.util.Date; import java.awt.Point; public class Point3D extends Point implements Cloneable { private int z = 0; private Date date = new Date(); public Object clone ( ) { Point3D copy = null; try { copy = (Point3D)super.clone(); } catch (Exception e) { return null; } copy.date = (Date)date.clone(); return copy; public static void main ( String args[] ) { Point3D p1 = new Point3D(); Point3D p2 = (Point3D)p1.clone(); System.out.println( p2.date ); //month becomes March p1.date.setMonth( 2 ); }

Listener interfaces

Listener interfaces ActionListener MouseListener MouseMotionListener (Mention sync vs. async event handling.)

ActionListener interface See http://docs.oracle.com/javase/6/docs/api/java/awt/event/ActionListener.html. One method: void actionPerformed ( ActionEvent e ); Invoked when an action occurs such as a button press.

Using the ActionListener import java.awt.event.ActionEvent; import java.awt.event.ActionListener; class Test implements ActionListener { public void actionPerformed ( ActionEvent e ) { } public static void main ( String p[] ) { Test t = new Test();

MouseListener interface

MouseListener interface void mouseClicked ( MouseEvent e ) Invoked when the mouse button has been clicked (pressed and released) on a component.

MouseListener interface void mousePressed ( MouseEvent e ) Invoked when a mouse button has been pressed on a component.

MouseListener interface void mouseReleased ( MouseEvent e ) Invoked when a mouse button has been released on a component.

MouseListener interface void mouseEntered ( MouseEvent e ) Invoked when the mouse enters a component.

MouseListener interface void mouseExited ( MouseEvent e ) Invoked when the mouse exits a component.

Using the MouseListener import java.awt.event.MouseEvent; import java.awt.event.MouseListener; class Test implements MouseListener { public void mouseClicked ( MouseEvent e ) { } public void mouseEntered ( MouseEvent e ) { } public void mouseExited ( MouseEvent e ) { } public void mousePressed ( MouseEvent e ) { } public void mouseReleased ( MouseEvent e ) { System.out.println( "mouseReleased: " + e ); } public static void main ( String p[] ) { Test t = new Test();

MouseMotionListener interface

MouseMotionListener interface void mouseDragged ( MouseEvent e ) Invoked when a mouse button is pressed on a component and then dragged. MOUSE_DRAGGED events will continue to be delivered to the component where the drag originated until the mouse button is released (regardless of whether the mouse position is within the bounds of the component). Due to platform-dependent Drag&Drop implementations, MOUSE_DRAGGED events may not be delivered during a native Drag&Drop operation.

MouseMotionListener interface void mouseMoved ( MouseEvent e ) Invoked when the mouse cursor has been moved onto a component but no buttons have been pushed.

Using the MouseMotionListener import java.awt.event.MouseEvent; import java.awt.event.MouseMotionListener; class Test implements MouseMotionListener { public void mouseDragged ( MouseEvent e ) { } public void mouseMoved ( MouseEvent e ) { } public static void main ( String p[] ) { Test t = new Test(); }