COMP 201 Java Programming Topic 5 Interfaces and

  • Slides: 45
Download presentation
COMP 201 Java Programming Topic 5: Interfaces and Inner Classes Readings: Chapter 6 1

COMP 201 Java Programming Topic 5: Interfaces and Inner Classes Readings: Chapter 6 1

COMP 201 Topic 5 / Slide 2 Interfaces/Outline l Introduction and An Example l

COMP 201 Topic 5 / Slide 2 Interfaces/Outline l Introduction and An Example l Basic issues Defining interfaces n Using interfaces n Interfaces and abstract classes n l More advanced issues Interfaces and callbacks n The Cloneable Interface n 2

COMP 201 Topic 5 / Slide 3 Introduction to Interfaces l An interface is

COMP 201 Topic 5 / Slide 3 Introduction to Interfaces l An interface is not a class but a set of requirements for classes that want to conform to the interface. l An interface consists of a collection constants and a collection of method with certain signatures (names plus parameter lists, function prototypes, function headers). l Interfaces never have instance fields and the methods in the interface are never implemented. l Interface provides a way to say that a class must implement certain methods (Ensure objects to have certain behaviors). It establishes a “protocol” between classes. So the supplier of some service states: “If your class conforms to a particular interface, then I’ll perform the service”. l Preferred method for implementing callback functions 3

COMP 201 Topic 5 / Slide 4 An Example l java. util. Arrays has

COMP 201 Topic 5 / Slide 4 An Example l java. util. Arrays has method static void sort(Object[] a) l Task: Use the method to sort an array of Employees l Problem: the method requires that the objects to be sorted must belong to classes that implements the Comparable interface (java. lang): public interface Comparable { int compare. To(Object b); } 4

COMP 201 Topic 5 / Slide 5 An Example l Modify Employee so that

COMP 201 Topic 5 / Slide 5 An Example l Modify Employee so that it implements the comparable interface: class Employee implements Comparable { … public int compare. To(Object other. Object) { Employee other = (Employee)other. Object; if (salary < other. salary) return -1; if (salary > other. salary) return 1; return 0; } … } 5

COMP 201 Topic 5 / Slide 6 An Example l Now we can use

COMP 201 Topic 5 / Slide 6 An Example l Now we can use the sort method of Arrays to sort an array of Employees: Employee[] staff = new Employee[3]; staff[0] = new Employee("Tony Tester", 38000); staff[1] = new Employee("Harry Hacker", 35000); staff[2] = new Employee("Carl Cracker", 75000); Arrays. sort(staff); // print out information about all Employee objects for (int i = 0; i < staff. length; i++) { Employee e = staff[i]; System. out. println("name=" + e. get. Name() + ", salary=" + e. get. Salary()); } // Employee. Sort. Test. java 6

COMP 201 Topic 5 / Slide 7 Defining Interfaces l General skeleton: public interface

COMP 201 Topic 5 / Slide 7 Defining Interfaces l General skeleton: public interface Nameof. Interface extends Another. Interface { method 1; method 2; … constant 1; constant 2; … } All methods are abstract by default, no need for modifier abstract n All fields are constants by default, no need for modifier static final n All methods and constants have public access by default, no need for modifier public. n 7

COMP 201 Topic 5 / Slide 8 Defining Interfaces l An example public interface

COMP 201 Topic 5 / Slide 8 Defining Interfaces l An example public interface Moveable { void move( doube x, double y); } public interface Powered extends Moveable { String power. Source(); int SPEED_LIMIT = 95; } 8

COMP 201 Topic 5 / Slide 9 Using Interfaces l To make a class

COMP 201 Topic 5 / Slide 9 Using Interfaces l To make a class implement an interface n Declare that your class implements that given interface class Employee implements Comparable n Provide definition of ALL methods in the interface. The public access modifier must be provided here. public int compare. To(Object other. Object) { Employee other = (Employee)other. Object; if (salary < other. salary) return -1; if (salary > other. salary) return 1; return 0; } 9

COMP 201 Topic 5 / Slide 10 Using interfaces l Although no multiple inheritance,

COMP 201 Topic 5 / Slide 10 Using interfaces l Although no multiple inheritance, a Java class can implement multiple interfaces class Employee implements Comparable, Cloneable l If a parent class implements an interface, subclass does not need to explicitly use the implement keyword. (Why? ) class Employee implements Comparable, Cloneable { public Object clone() {…} } class manager extends Employee { public Object clone() {…} } 10

COMP 201 Topic 5 / Slide 11 Using Interfaces l Interfaces are not classes.

COMP 201 Topic 5 / Slide 11 Using Interfaces l Interfaces are not classes. You cannot instantiate interfaces, i. e. cannot use the new operator with an interface new Comparable(); // illegal l Can declare interface variables Comparable x; // x can refer to an object that has the // behavior specified in Comparable x = new Employee(); //ok if Employee implements Comparable l Can use instance. Of if ( x instance. Of Comparable) … // Does x have the behavior specified in Comparable? 11

COMP 201 Topic 5 / Slide 12 Interfaces and Abstract Classes l Interfaces cannot

COMP 201 Topic 5 / Slide 12 Interfaces and Abstract Classes l Interfaces cannot have static methods, abstract classes can l Interfaces cannot contain implementations of methods, abstract classes can l Interfaces cannot have fields, abstract classes can. abstract class Person { public Person(String n) { name = n; } public abstract String get. Description(); public String get. Name() { return name; } private String name; } 12

COMP 201 Topic 5 / Slide 13 Interfaces and Abstract Classes l Are interfaces

COMP 201 Topic 5 / Slide 13 Interfaces and Abstract Classes l Are interfaces a necessity (from the point of view of language design) given that we have abstract classes? n In order to sort an array of Employees, can we simply do the following? abstract class Comparable { public abstract int Compare. To(Object other); } class Employee extends Compareable { public int Compare. To(Object other) {…} … } 13

COMP 201 Topic 5 / Slide 14 Interfaces and Abstract Classes n Cannot do

COMP 201 Topic 5 / Slide 14 Interfaces and Abstract Classes n Cannot do this if Employee already extends another class Employee extends Person … Because we cannot have class Employee extends Person, Comparable … 14

COMP 201 Topic 5 / Slide 15 Interfaces and Callbacks l Interfaces provide a

COMP 201 Topic 5 / Slide 15 Interfaces and Callbacks l Interfaces provide a good way to write callbacks The program Timer. Test. java prints “The time now is …” every second. n How does it work? – There is a timer (javax. swing. Timer) that keeps track of time. n – How do we tell the timer what to do when the time interval (1 second) has elapsed? – Answer: Callbacks l In many languages, we supply the name of a function the timer should call periodically. l In Java, we supply the timer with an object of some class. 15

COMP 201 Topic 5 / Slide 16 Interfaces and Callbacks l Of course, the

COMP 201 Topic 5 / Slide 16 Interfaces and Callbacks l Of course, the timer needs to know which method of the object to call. But how? l The timer requires that the object must belong to a class that implements the Action. Listener interface java. awt. event. Action. Listener public interface Action. Listener { void action. Performed(Action. Event event); } l The timer calls the action. Performed method when the time interval has elapsed. 16

COMP 201 Topic 5 / Slide 17 Interfaces and Callbacks Class for the listener

COMP 201 Topic 5 / Slide 17 Interfaces and Callbacks Class for the listener object: class Time. Printer implements Action. Listener { public void action. Performed(Action. Event event) { Date now = new Date(); //java. util System. out. println("The time now is " + now); } } l 17

COMP 201 Topic 5 / Slide 18 Interfaces and Callbacks public class Timer. Test

COMP 201 Topic 5 / Slide 18 Interfaces and Callbacks public class Timer. Test { public static void main(String[] args) { Action. Listener listener = new Time. Printer(); // construct a timer that calls the listener // once every 1 second Timer t = new Timer(1000, listener); t. start(); // start timer // continue until told to stop JOption. Pane. show. Message. Dialog(null, "Quit program? "); System. exit(0); } } 18

COMP 201 Topic 5 / Slide 19 Diversion/Protected Access Again l l protected fields/methods

COMP 201 Topic 5 / Slide 19 Diversion/Protected Access Again l l protected fields/methods can be accessed by subclasses (with a caveat) and classes in the same package. Example: package Greek; public class Alpha { protected int iamprotected; protected void protected. Method() {…} } package Greek; class Gamma { void access. Method() { Alpha a = new Alpha(); a. iamprotected = 10; // legal a. protected. Method(); // legal } } 19

COMP 201 Topic 5 / Slide 20 Diversion/Protected Access Again l Caveat: Subclass in

COMP 201 Topic 5 / Slide 20 Diversion/Protected Access Again l Caveat: Subclass in a different package can only access protected fields and methods on objects of the subclass and it’s subclasses package Latin; import Greek. *; class Delta extends Alpha { void access. Method(Alpha a, Delta d) { a. iamprotected = 10; // illegal d. iamprotected = 10; // legal a. protected. Method(); // illegal d. protected. Method(); // legal } } 20

COMP 201 Topic 5 / Slide 21 The Cloneable Interface l A clone of

COMP 201 Topic 5 / Slide 21 The Cloneable Interface l A clone of an object is a new object that has the same state as the original but with a different identity. In particular you can modify the clone without affecting the original. l Copying objects using the clone() method of Object l Default implementation: n n n Copies bit-by-bit. Ok for copying objects whose fields are primitive types Not ok for cloning objects with reference fields. 21

COMP 201 Topic 5 / Slide 22 The Cloneable Interface l Employee original =

COMP 201 Topic 5 / Slide 22 The Cloneable Interface l Employee original = new Employee("John Q. Public", 50000); original. set. Pay. Day(2000, 1, 1); Employee tmp = original. clone(); Actually compiler error. But let’s pay. Day not copied! assume it is alright for now original …. pay. Day tmp … 2000 What would happen if tmp was paid 14 days earlier? tmp. pay. Day. add. Pay. Day(-14); But this also affects original. pay. Day! 22

COMP 201 Topic 5 / Slide 23 The Cloneable Interface l Because cloning is

COMP 201 Topic 5 / Slide 23 The Cloneable Interface l Because cloning is tricky, the clone method of Object is protected. l A subclass of Object, which presumably lives in a different package, can call the protected clone method only on its own objects, i. e. to clone its own objects. l You cannot simply invoke an. Object. Of. X. Clone() in class Y to clone an. Objectof. X. l In order to clone objects of a class, you must have the class redefine the clone method and change its access modifier to public. n AND declare that the class implements the Cloneable interface. (Java’s way to enforce you to override the clone method. ) n 23

COMP 201 Topic 5 / Slide 24 The Cloneable Interface l Suppose we want

COMP 201 Topic 5 / Slide 24 The Cloneable Interface l Suppose we want to clone Employee. public class Employee implements Cloneable { … public Object clone() { try { // call Object. clone() Employee cloned = (Employee)super. clone(); // clone mutable fields cloned. pay. Day=(Gregorian. Calendar)pay. Day. clone(); return cloned; } catch (Clone. Not. Supported. Exception e) {return null; } } } // Clone. Test. java Correct Clone //Clone. Test 1. java Incorrect clone 24

COMP 201 Topic 5 / Slide 25 The Cloneable Interface l Employee original =

COMP 201 Topic 5 / Slide 25 The Cloneable Interface l Employee original = new Employee("John Q. Public", 50000); original. set. Pay. Day(2000, 1, 1); Employee tmp = original. clone(); pay. Day copied! original …. pay. Day payday …. 2000 cloned What would happen if cloned was paid 14 days earlier? cloned. pay. Day. add. Pay. Day(-14); This has NO affects original. pay. Day! 25

COMP 201 Topic 5 / Slide 26 The Cloneable Interface l Redefinition of clone

COMP 201 Topic 5 / Slide 26 The Cloneable Interface l Redefinition of clone method is necessary even when the default is good enough. Redefine clone to be public, call super. clone() and catch the Clone. Not. Supported. Exception. class Person implements Cloneable { … public Object clone() { try { return super. clone(); } catch (Clone. Not. Supported. Exception e) { return null; } //This won’t happen, since we are Cloneable } } 26

COMP 201 Topic 5 / Slide 27 The Cloneable Interface l What are the

COMP 201 Topic 5 / Slide 27 The Cloneable Interface l What are the methods in Cloneable? l The clone method is inherited from class Object. It is not a method of the Cloneable interface. l The Cloneable interface has no methods and hence called a tagging interface. l It is used to indicate that the class designer understand the clone process and can decide correctly whether to refine the clone method. 27

COMP 201 Topic 5 / Slide 28 Inner Class/Outline l Introduction l Inner classes

COMP 201 Topic 5 / Slide 28 Inner Class/Outline l Introduction l Inner classes through an example l Local inner classes l Anonymous Inner classes l Static inner classes 28

COMP 201 Topic 5 / Slide 29 Introduction Inner Classes l l l An

COMP 201 Topic 5 / Slide 29 Introduction Inner Classes l l l An inner class is a class defined inside another class Similar to nested classes in C++, but more flexible & more powerful. Useful because: l Object of inner class can access private fields and methods of outer class. l Can be hidden from other classes in the same package. Good for, e. g. , nodes in linked lists or trees. l Anonymous inner classes are handy when defining callbacks on the fly l Convenient when writing event-driven programs. 29

COMP 201 Topic 5 / Slide 30 Inner Classes Through An Example l Task:

COMP 201 Topic 5 / Slide 30 Inner Classes Through An Example l Task: Write a program that adds interest to a bank account periodically. Following the Timer. Test example, we write public class Add. Interest { public static void main(String[] args) { // construct a bank account with initial balance of $10, 000 Bank. Account account = new Bank. Account(10000); // construct listerner object to accumulate interest at 10% Action. Listener adder = new Interest. Adder(10, account); // construct timer that call listener every second Timer t = new Timer(1000, adder); t. start(); … // termination facility } } // Add. Interest. java 30

class Interest. Adder implements Action. Listener …. //print out current balance { public Interest.

class Interest. Adder implements Action. Listener …. //print out current balance { public Interest. Adder(double a. Rate, Bank. Account a. Account) { rate = a. Rate; account = a. Account; } public void action. Performed(Action. Event event) { // update interest double interest = account. get. Balance() * rate/ 100; account. set. Balance( account. get. Balance()+interest); } private Bank. Account account; private double rate; } n Note that Interest. Adder requires Bank. Account class to provide public accessor get. Balance and mutator set. Balance. 31

COMP 201 Topic 5 / Slide 32 Inner Classes Through An Example n The

COMP 201 Topic 5 / Slide 32 Inner Classes Through An Example n The Bank. Account class Bank. Account { public Bank. Account(double initial. Balance) { balance = initial. Balance; } public void set. Balance( double balance) { this. balance = balance; } public double get. Balance() { return balance; } private double balance; } 32

COMP 201 Topic 5 / Slide 33 Inner Classes Through An Example l The

COMP 201 Topic 5 / Slide 33 Inner Classes Through An Example l The program Add. Interest. java works l BUT, not satisfactory: n Bank. Account has public accessor get. Balance and mutator set. Balance. n Any other class can read and change the balance of an account! l Inner classes provide a better solution n Make Interest. Adder an inner private class of Bank. Account n Since inner classes can access fields and methods of outer classes, Bank. Account no longer needs to provide public accessor and mutator. n The inner class Interest. Adder can only be used inside Bank. Acccount. 33

COMP 201 Topic 5 / Slide 34 Inner Classes Through An Example class Bank.

COMP 201 Topic 5 / Slide 34 Inner Classes Through An Example class Bank. Account { … private double balance; private class Interest. Adder implements Action. Listener { public Interest. Adder(double a. Rate) { rate = a. Rate; } Access field of outer class directly } } public void action. Performed(Action. Event event) { // update interest double interest = balance * rate / 100; balance += interest; …// print out current balance } private double rate; Access field of outer class 34 directly

COMP 201 Topic 5 / Slide 35 Inner Classes Through An Example l Only

COMP 201 Topic 5 / Slide 35 Inner Classes Through An Example l Only inner classes can be private. l Regular classes always have either package or public visibility. 35

COMP 201 Topic 5 / Slide 36 Inner Classes Through An Example l Interest.

COMP 201 Topic 5 / Slide 36 Inner Classes Through An Example l Interest. Adder can only be used inside Bank. Account, so we need to place timer inside Bank. Account also: class Bank. Account { public Bank. Account(double initial. Balance) { balance = initial. Balance; } public void start(double rate) { Action. Listener adder = new Interest. Adder(rate); Timer t = new Timer(1000, adder); t. start(); } … } 36

COMP 201 Topic 5 / Slide 37 Inner Classes Through An Example l The

COMP 201 Topic 5 / Slide 37 Inner Classes Through An Example l The driver class: public class Inner. Class. Test { public static void main(String[] args) { // construct a bank account with initial balance of $10, 000 Bank. Account account = new Bank. Account(10000); // start accumulating interest at 10% account. start(10); JOption. Pane. show. Message. Dialog(null, "Quit program? "); System. exit(0); } } //Inner. Class. Test. java 37

COMP 201 Topic 5 / Slide 38 Local Inner Classes l Note that in

COMP 201 Topic 5 / Slide 38 Local Inner Classes l Note that in Bank. Account class: l The class Interest. Adder is used only once in method start. l In this case, Java lets you define class Interest. Adder locally inside method start. 38

COMP 201 Topic 5 / Slide 39 Local Inner Classes public void start(double rate)

COMP 201 Topic 5 / Slide 39 Local Inner Classes public void start(double rate) { class Interest. Adder implements Action. Listener { public Interest. Adder(double a. Rate) { rate = a. Rate; } public void action. Performed(Action. Event event) { double interest = balance * rate / 100; balance += interest; …// print out current balance } private double rate; } Action. Listener adder = new Interest. Adder(rate); Timer t = new Timer(1000, adder); t. start(); 39

COMP 201 Topic 5 / Slide 40 Local Inner Classes l A local class

COMP 201 Topic 5 / Slide 40 Local Inner Classes l A local class is never declared with an access modifier. Its scope restricted to the scope of the method within which it is defined. l Local class can be accessed only by the method within which it defined. l It can access local variables if there are final. 40

COMP 201 Topic 5 / Slide 41 Local Inner Classes public void start( final

COMP 201 Topic 5 / Slide 41 Local Inner Classes public void start( final double rate) { class Interest. Adder implements Action. Listener { // no constructor now needed in this case public void action. Performed(Action. Event event) { double interest = balance * rate / 100; balance += interest; …// print out current balance } // the rate field is gone. } Action. Listener adder = new Interest. Adder(); Timer t = new Timer(1000, adder); t. start(); } 41

COMP 201 Topic 5 / Slide 42 Anonymous Inner Classes l l Anonymous inner

COMP 201 Topic 5 / Slide 42 Anonymous Inner Classes l l Anonymous inner classes take this one step further. Kind of replacing the usage of Interest. Adder with its definition. public void start( final double rate) { Action. Listener adder = new Action. Listener() { public void action. Performed(Action. Event event) { double interest = balance * rate / 100; balance += interest; … // print out current balance } } Timer t = new Timer(1000, adder); t. start(); 42 } // Anonymous. Inner. Class. Test. java

COMP 201 Topic 5 / Slide 43 Anonymous Inner Classes l l General syntax:

COMP 201 Topic 5 / Slide 43 Anonymous Inner Classes l l General syntax: n new some. Interface() {…} creates an object of an anonymous inner class that implements some. Interface n new some. Class( construction. Parameters){…} creates an object of an anonymous inner class that extends some. Class. Note: An anonymous inner class cannot have constructors n Reason: constructors must have the same name as class and as anonymous class has no name. n Implication: Construction parameters passed to super class constructor. n Implication: An anonymous class that implements an interface cannot have construction parameters. 43

COMP 201 Topic 5 / Slide 44 Static Inner Classes l Static inner classes

COMP 201 Topic 5 / Slide 44 Static Inner Classes l Static inner classes are inner classes that do not have reference to outer class object. class Array. Alg { public static class Pair { public Pair(double f, double s) {…} public double get. First(){…} public double get. Second(){…} private double first; private double second; } } public static Pair minmax(double[] d) { // finds minimum and maximum elements in array return new Pair(min, max); } Same as nested classes in C++ 44

COMP 201 Topic 5 / Slide 45 Static Inner Classes l Static inner classes

COMP 201 Topic 5 / Slide 45 Static Inner Classes l Static inner classes can be used to avoid name clashes. l For example, the Pair class in our example is known to the outside as Array. Alg. Pair. l Avoid clashing with a Pair class that is defined elsewhere and has different contents, e. g. a pair of strings. Static. Inner. Class. Test. java 45