Revised 01/09/05 About This Lecture Slide # 2 Data Abstraction - Interfaces and Implementations In this lecture we will learn how Java objects and classes can be used to build abstract data types. CMPUT 115 - Lecture 2 Department of Computing Science University of Alberta \ Some code in this lecture is based on code from the book: Java Structures by Duane A. Bailey or the companion structure package Slide # 3 Slide # 4 Outline Object Concepts Interface Use Implementation Java interfaces Object Concepts An object has: a private state A set of resources that it provides. Let s call this its public protocol Each object is an instance of a class. The class defines the public protocol, so all objects of a class have the same protocol. The state of an object differentiates it from other objects in the same class. Slide # 5 Slide # 6 Object Class, Protocol and State Public protocol external request private private state private state private state public interface state public public interface interface public protocol class In Java, the public protocol of a class includes: The name of the superclass Public variable declarations Public constructor declarations Public message declarations Public static method declarations 1
Slide # 7 Slide # 8 Example: Point Class Even before you knew how to write your own classes in CMPUT 114, you could create objects from classes that other people had written You relied on documentation to tell you about the publicly-accessible resources in a class Example - using the Point class in awt package: http://www-csfy.cs.ualberta.ca/~c114/jdk1.2.2/docs/api/java/awt/point.html Interface, Implementation & Use There are three aspects for any class: Protocol: a description of the resources that the class provides. Implementation: the code that describes the private state of instances and implements the computational resources of the class. Use: code in a using class causes new instances of the used class to be created and invokes computations on these instances. We will now investigate these 3 aspects in relation to the Ratio class Protocol - Ratio Class (slide 1) public class Ratio { /* an object for storing a fraction */ public Ratio(int top, int bottom) /* a constructor used to construct a new object */ public int getnumerator() /* post: return the numerator of the fraction */ Slide # 9 Protocol - Ratio Class (slide 2) Slide # 10 public double value() /* post: returns the real value equivalent to ratio */ public Ratio add(ratio other) /* pre: other is non-null post: return new fraction - the sum of this and other */ public int getdenominator() /* post: return the denominator of the fraction */ Slide # 11 Slide # 12 Using classes What can we do with a class once we ve defined it how can we use it? In Java, class A can use class B by: Creating instances of class B. Sending messages to instances of class B. Invoking static methods from class B. Using variables that are declared in class B. Using message arguments that are declared to be of class B. Using the Ratio Class public class SomeClass { public static void main(string[] args) { Ratio r1; Ratio r2; Ratio r3; r1 = new Ratio(3,5); // r1 == 3/5 (0.6) r2 = new Ratio(1,4); // r2 == 1/4 (0.25) r3 = r1.add(r2); // r1 still 3/5, r2 still 1/4 // r3 == 17/20 (0.85) r1 = r1.add(r2); // r1 == 17/20 System.out.println(r1.value()); // 0.85 printed 2
Slide # 13 Slide # 14 Implementation In Java, a class implementation includes: Bindings for static variables Declarations of instance variables Static method code Constructor code Instance method code (to handle messages) Implementation - Ratio Class (slide 1) public class Ratio { /* an object for storing a fraction */ protected int numerator; // numerator of ratio protected int denominator; // denominator of ratio public Ratio(int top, int bottom) { /* pre: bottom!= 0 post: constructs a ratio equivalent to top/bottom */ this.numerator = top; this.denominator = bottom; Slide # 15 Slide # 16 Implementation - Ratio Class -2 public int getnumerator() { /* post: return the numerator of the fraction */ return this.numerator; public int getdenominator() { /* post: return the denominator of the fraction */ return this.denominator; Implementation - Ratio Class -3 public double value() { /* post: returns the real value equivalent to ratio */ return (double)this.numerator /(double)this.denominator; public Ratio add(ratio other) { /* pre: other is non-null post: return new fraction - the sum of this and other */ return new Ratio(this.numerator*other.denominator+ this.denominator*other.numerator, this.denominator*other.denominator); Slide # 17 Slide # 18 Java Interfaces For many classes, the protocol and the implementation are in the same file. However, Java has a specific feature called an Interface that can be used to separate the protocol of a class from its implementation Unfortunately, interfaces are not always used! A Java interface contains no code, only message signatures. Benefits of Using Interfaces Java does not allow multiple inheritance: interfaces address this issue Interfaces exploit the concept of type conformance: a type can conform to another if it has the same set of methods (and maybe some extras) These two types don t have to be related by inheritance more freedom! Interfaces allow a class to specify that its instances can be used anywhere that a matching interface is required 3
Slide # 19 Slide # 20 Inheritance versus interfaces Inheritance: a subclass shares a common structure and behaviour with its superclass Example Interface - IntRectangle We will now learn how to write and implement an interface. Interface: classes that implement an interface share common behaviours (but not structure) We will write: IntRectangle (the interface) IntRectangleI class (implements IntRectangle interface) IntRectangleP class (implements IntRectangle interface) Java Interface - IntRectangle Slide # 21 Implementing Java Interfaces Slide # 22 public interface IntRectangle { public Point origin(); /* post: returns the Point at the upper left. */ public Point corner(); /* post: returns the Point at the lower right. */ public int height(); /* post: returns the size in the vertical direction. */ public int width(); /* post: returns size in the horizontal direction. */ A Java class is used to implement a Java Interface. The class must provide code for every message in the Java Interface. The class name must be different from the Java Interface name. Slide # 23 Slide # 24 Class - IntRectangleP (slide 1) Class - IntRectangleP (slide 2) public class IntRectangleP implements IntRectangle { protected Point origin; // upper left protected Point corner; // lower right public IntRectangleP (Point startpoint, Point endpoint){ /* post: constructs an IntRectangleP with the given upper left and lower right Points. */ this.origin = startpoint; this.corner = endpoint; public IntRectangleP (int x, int y, int width, int height) { /* post: constructs an IntRectangleP whose upper left point has the given x and y coordinates, the given width in the x direction and the given height in the y direction. */ this.origin = new Point(x, y); this.corner = new Point(x + width, y + height); public Point origin() { /* post: returns the Point at the upper left. */ return this.origin; 4
Class - IntRectangleP (slide 3) public Point corner() { /* post: returns the Point at the lower right. */ return this.corner; public int height() { /* post: returns the size in the vertical direction. */ return (this.corner.y - this.origin.y); public int width() { /* post: returns size in the horizontal direction. */ Slide # 25 Slide # 26 Multiple Classes can Implement a Java Interface We can have an arbitrary number of classes that implement the same interface For example, we could have another class that implements the IntRectangle interface, named the IntRectangleI class. return (this.corner.x - this.origin.x); Slide # 27 Slide # 28 Class - IntRectangleI (slide 1) public class IntRectangleI implements IntRectangle { protected int x; // x coord of upper left protected int y; // y coord of upper left protected int width; // size in x direction; protected int height; // size in y direction; public IntRectangleI (Point startpoint, Point endpoint) { /* post: constructs an IntRectangleI with the given upper left and lower right Points. */ this.x = startpoint.x; this.y = startpoint.y; this.width = endpoint.x - this.x; this.height = endpoint.y - this.y; Class - IntRectangleI (slide 2) public IntRectangleI (int x, int y, int width, int height) { /* post: constructs an IntRectangleI whose upper left point has the given x and y coordinates, the given width in the x direction and the given height in the y direction. */ this.x = x; this.y = y; this.width = width; this.height = height; public Point origin() { /* post: returns the Point at the upper left. */ return new Point(this.x, this.y); Class - IntRectangleI (slide 3) public Point corner() { /* post: returns the Point at the lower right. */ return new Point(this.x + this.width, this.y + this.height); public int height() { /* post: returns the size in the vertical direction. */ return this.height; public int width() { /* post: returns size in the horizontal direction. */ return this.width; Slide # 29 Slide # 30 Declaring Variables using Interfaces We can declare variables to be the Interface type, but must create instances of the implementation classes to bind them to. Can t instantiate an interface! Parameters can also be declared to be an Interface type, allowing us to write methods that work for instances of different classes. 5
` ` ` ` _ Slide # 31 Slide # 32 Using IntRectangle Generic method to compute area Public class EgClass { public void main(string args[]) { IntRectangle rectangle; rectangle = new IntRectangleP(new Point(3, 4), new Point(5, 9)); System.out.println(EgClass.area(rectangle)) ; rectangle = new IntRectangleI(3, 4, 2, 5); System.out.println(EgClass.area(rectangle)) ; public static int area(intrectangle r) { /* post: returns the rectangle s area. */ return r.width() * r.height(); r might be bound to an instance of IntRectangleP or to an instance of InRectangleI. Another Example of an Interface Slide # 33 actionperformed( ) Slide # 34 In CMPUT 114 you wrote applets that contained buttons (or other Components), which the user could click on Your applet had a signature like this:! " # $ %& ' ( %) *,+ Only need this last part if your applet is to respond to user s actions (e.g. mouse click, click on button, enter text in text field etc.) The ActionListener interface dictates that every implementing class defines an actionperformed() method if not defined, compiler gives us an error message For example, in class MyClass: -,.0/2143 5"6$7398;:<5 =>3 72? @<A$B%C)7BEDFA<8G&Ḧ 5=E3 7?I 6$A$?,=JA<K L MNMNMO<O0P Q$R,S;TVU2W2T2XSW,PTZY;T&Q[TVUS\W,P<TV]ZQ<^MZMNM Slide # 35 Slide # 36 How it works For more information When the user clicks a button, the button's action listeners are notified. See the following: 1. http://java.sun.com/docs/books/tutorial/uiswing/over view/event.html The button creates an ActionEvent object, reference is passed to listener. This causes the action listener's actionperformed() method to be invoked 2. http://wwwcsfy.cs.ualberta.ca/~c114/jdk1.2.2/docs/api/java/awt/ event/actionlistener.html ActionEvent object contains all information about the event that has occurred you write code that extracts that information and determines what should happen in response to event 3. http://wwwcsfy.cs.ualberta.ca/~c114/jdk1.2.2/docs/api/java/awt/ event/actionevent.html 6
Slide # 37 Summary: Interface definition An interface defines a protocol of behavior that can be implemented by any class anywhere in the class hierarchy An interface defines a set of methods but does not implement them. A class that implements the interface agrees to implement all the methods defined in the interface, thereby agreeing to certain behavior Interfaces can also define constants Sun Microsystems (web site tutorial) 7