COMP201 Java Programming Topic 6: Interfaces and Inner Classes Readings: Chapter 6.

Slides:



Advertisements
Similar presentations
Lecture 5: Interfaces.
Advertisements

 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).
Inner Classes. Nested Classes  An nested class is a class that is defined inside another class.  To this point we have only studied top-level classes.
COMP201 Topic 8 / Slide 1 COMP201 Java Programming Topic 6: Interfaces and Inner Classes Readings: Chapter 6.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Inheritance and Polymorphism.
Lecture 17 Abstract classes Interfaces The Comparable interface Event listeners All in chapter 10: please read it.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
Fall 2007CS 2251 Inheritance and Class Hierarchies Chapter 3.
1 More on Inheritance Overview l Object: The father of all classes l Casting and Classes l Object Cloning l Importance of Cloning.
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.
Slides prepared by Rose Williams, Binghamton University Chapter 13 Interfaces and Inner Classes.
1 Java Object Model Part 2: the Object class. 2 Object class Superclass for all Java classes Any class without explicit extends clause is a direct subclass.
Lecture 18 Review the difference between abstract classes and interfaces The Cloneable interface Shallow and deep copies The ActionListener interface,
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?
16-Aug-15 Air Force Institute of Technology Electrical and Computer Engineering Object-Oriented Programming in Java Topic : Interfaces, Copying/Cloning,
GETTING INPUT Simple I/O. Simple Input Scanner scan = new Scanner(System.in); System.out.println("Enter your name"); String name = scan.nextLine(); System.out.println("Enter.
Appendix A.2: Review of Java and Object-Oriented Programming: Part 2 “For the object-oriented project, remember that the primary unit of decomposition.
Chapter 6 Class Inheritance F Superclasses and Subclasses F Keywords: super F Overriding methods F The Object Class F Modifiers: protected, final and abstract.
COP INTERMEDIATE JAVA Designing Classes. Class Template or blueprint for creating objects. Their definition includes the list of properties (fields)
Introduction to Java Prepared by: Ahmed Hefny. Outline Classes Access Levels Member Initialization Inheritance and Polymorphism Interfaces Inner Classes.
Programming Languages and Paradigms Object-Oriented Programming (Part II)
The Java Programming Language
Inheritance and Polymorphism Daniel Liang, Introduction to Java Programming.
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.
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.
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Chapter 10 - Interfaces.
Chapter 3 Inheritance and Polymorphism Goals: 1.Superclasses and subclasses 2.Inheritance Hierarchy 3.Polymorphism 4.Type Compatibility 5.Abstract Classes.
1 final (the keyword, not the exam). 2 Motivation Suppose we’ve defined an Employee class, and we don’t want someone to come along and muck it up  E.g.,
Chapter 14 Abstract Classes and Interfaces. Abstract Classes An abstract class extracts common features and functionality of a family of objects An abstract.
Advanced Programming Rabie A. Ramadan vpro/ Lecture 4.
COP INTERMEDIATE JAVA Designing Classes. Class Template or blueprint for creating objects. Their definition includes the list of properties (fields)
Inheritance. Inheritance - Introduction Idea behind is to create new classes that are built on existing classes – you reuse the methods and fields and.
Chapter 5 Objects and Classes Inheritance. Solution Assignments 3 & 4 Review in class…..
1 Abstract Classes and Interfaces. 2 The abstract Modifier  The abstract class –Cannot be instantiated –Should be extended and implemented in subclasses.
OOP in C++ CS 124. Program Structure C++ Program: collection of files Source (.cpp) files be compiled separately to be linked into an executable Files.
Java Class Structure. Class Structure package declaration import statements class declaration class (static) variable declarations* instance variable.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 9 Inheritance and.
Chapter 7: Class Inheritance F Superclasses and Subclasses F Keywords: super and this F Overriding methods F The Object Class F Modifiers: protected, final.
Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class.
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.
Inheritance and Subclasses CS 21a. 6/28/2004 Copyright 2004, by the authors of these slides, and Ateneo de Manila University. All rights reserved L16:
1 Interface Design. 2 concept An interface is a way to describe what classes should do, without specifying how they should do it. It’s not a class but.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
Inheritance and Class Hierarchies Chapter 3. Chapter Objectives  To understand inheritance and how it facilitates code reuse  To understand how Java.
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
(c) University of Washington06-1 CSC 143 Java Inheritance Tidbits.
Chapter 4: More Object Concepts. Objectives Understand blocks and scope Overload a method Avoid ambiguity Create and call constructors with parameters.
1 Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
Classes Revisited Chapter 8.
POLYMORPHISM Chapter 6. Chapter Polymorphism  Polymorphism concept  Abstract classes and methods  Method overriding  Concrete sub classes and.
OOP Basics Classes & Methods (c) IDMS/SQL News
Reference Types CSE301 University of Sunderland Harry R Erwin, PhD.
COP INTERMEDIATE JAVA Inheritance, Polymorphism, Interfaces.
Classes CS 162 (Summer 2009). Parts of a Class Instance Fields Methods.
Object Oriented Programming. Constructors  Constructors are like special methods that are called implicitly as soon as an object is instantiated (i.e.
Class Inheritance Part II: Overriding and Polymorphism Corresponds with Chapter 10.
Inheritance and Polymorphism
Comp 249 Programming Methodology
Computer Science II Exam 1 Review.
Chapter 9 Inheritance and Polymorphism
Topic 5: Interfaces and Inner Classes
Lecture 4: Interface Design
Introduction interface in Java is a blueprint of a class. It has static constants and abstract methods only. An interface is a way to describe what classes.
Java Programming Language
Interfaces.
Chapter 8 Class Inheritance and Interfaces
Presentation transcript:

COMP201 Java Programming Topic 6: Interfaces and Inner Classes Readings: Chapter 6

COMP201 Topic 6 / Slide 2 Interfaces/Outline l Interfaces are a way to describe what classes should do without specifying how they should do it. l Outline n Interface basics –Introduction –Defining interfaces –Using interfaces n Interfaces vs abstract classes n Callbacks via interfaces: common use of interfaces The Cloneable Interface: a special interface

COMP201 Topic 6 / Slide 3 Introduction to Interfaces l Slide 55 of Topic 4 Employee inherits the equals method from Object. –Logical error if not refined The Object class gives us one way to do generic programming int find(Object[]a, Object key) { … if (a[i].equals(key)) return i; … } The function can be applied to objects of any class provided that the equals method is properly defined for that class Employee[] staff = new Employee[10]; Employee harry; … int n = find(staff, harry); Assuming Employee has method public boolean equals(). Alg0.java FindTest0.java

COMP201 Topic 6 / Slide 4 l Use interfaces to ensure that equality test properly implemented 1. Define interface public interface HasMyEquals { boolean myEquals(Object key); } 2. Change signature of the find method public static Object find( HasMyEquals[] A, Object key) { …if ( A[i].myEquals( key ) )…} 3. Consequences when writing Employee 1.Must implement the HasMyEquals interface Class Employee implements HasMyEquals {…} 2.Must provide myEquals method boolean myEquals(Object k) {…} Introduction to Interfaces HasMyEquals.java, Alg.java EmployeeTest.java

COMP201 Topic 6 / Slide 5 Interfaces/Outline l Outline n Interface basics –Introduction –Defining interfaces –Using interfaces n Interfaces vs abstract classes n Callbacks via interfaces: common use of interfaces n The Cloneable Interface: a special interface

COMP201 Topic 6 / Slide 6 Defining Interfaces l General skeleton: public interface NameofInterface [extends AnotherInterface] { method1; method2; … constant1; constant2; … } All methods are abstract by default, no need for modifier abstract All fields are constants by default, no need for modifier static final All methods and constants have public access by default, no need for modifier public.

COMP201 Topic 6 / Slide 7 Defining Interfaces l An example public interface Moveable { void move( doube x, double y); } public interface Powered extends Moveable { String powerSource(); int SPEED_LIMIT = 95; }

COMP201 Topic 6 / Slide 8 Interfaces/Outline l Outline n Interface basics –Introduction –Defining interfaces –Using interfaces n Interfaces vs abstract classes n Callbacks via interfaces: common use of interfaces n The Cloneable Interface: a special interface

COMP201 Topic 6 / Slide 9 Using Interfaces n Interface to use in in the following: java.lang.Comparable Public interface Comparable { int compareTo(Object other); } n When to use? When defining a class n How? –Declare that your class implements that given interface class Employee implements Comparable { –Provide definition of methods in the interface. The public access modifier must be provided here. public int compareTo(Object otherObject) // argument type must { Employee other = (Employee)otherObject; // match definition if (salary < other.salary) return -1; if (salary > other.salary) return 1; return 0; } n If some methods of the interface are not implemented, the class must be declared as abstract (why?)

COMP201 Topic 6 / Slide 10 l Why do I need to have my class implement an interface? Employee now implements Comparable, so what? Can use the sorting service provided by the Array s class –public static void sort(Object[] a)Object l Sorts the specified array of objects into ascending order, according to the natural ordering of its elements. l All elements in the array must implement the Comparable interface. … Using Interfaces EmployeeSortTest.java

COMP201 Topic 6 / Slide 11 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() {…} }

COMP201 Topic 6 / Slide 12 Using Interfaces 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 Can use instanceOf if ( x instanceOf Comparable) … // Does x have the behavior specified in Comparable?

COMP201 Topic 6 / Slide 13 Interfaces/Outline l Outline n Interface basics –Introduction –Defining interfaces –Using interfaces n Interfaces vs abstract classes n Callbacks via interfaces: common use of interfaces n The Cloneable Interface: a special interface

COMP201 Topic 6 / Slide 14 Interfaces and Abstract Classes l Interfaces are more abstract than abstract classes. n Interfaces cannot have static methods, abstract classes can n Interfaces cannot contain implementations of methods, abstract classes can n Interfaces cannot have fields, abstract classes can. abstract class Person { public Person(String n) { name = n;} public abstract String getDescription(); public String getName() { return name;} private String name; }

COMP201 Topic 6 / Slide 15 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 CompareTo(Object other);} Void sort(Comparable[] A) class Employee extends Compareable { public int CompareTo(Object other) {…} … } Interfaces and Abstract Classes

COMP201 Topic 6 / Slide 16 n Cannot do this if Employee already extends another class class Employee extends Person … Because we cannot have class Employee extends Person, Comparable … Interfaces and Abstract Classes

COMP201 Topic 6 / Slide 17 Interfaces/Outline l Outline n Interface basics –Introduction –Defining interfaces –Using interfaces n Interfaces vs abstract classes n Callbacks via interfaces: common use of interfaces n The Cloneable Interface: a special interface

COMP201 Topic 6 / Slide 18 Interfaces and Callbacks l Interfaces provide a good way to write callbacks The program TimerTest.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. –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.

COMP201 Topic 6 / Slide 19 l Questions n What method of the object that the timer should invoke? n How do we make sure that the object has the method? l Solution: The ActionListener interface java.awt.event.ActionListener public interface ActionListener { void actionPerformed(ActionEvent event); } n Timer t = new Timer(int Delay, ActionListener obj); The timer calls the actionPerformed method when the time interval has elapsed. Interfaces and Callbacks

COMP201 Topic 6 / Slide 20 l Make sure listener object has the methods: l It must be an object of class that implements that ActionListener class TimePrinter implements ActionListener { public void actionPerformed(ActionEvent event) { Date now = new Date(); //java.util System.out.println("The time now is " + now); } Interfaces and Callbacks

COMP201 Topic 6 / Slide 21 public class TimerTest { public static void main(String[] args) { ActionListener listener = new TimePrinter(); // 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 JOptionPane.showMessageDialog(null,"Quit program?"); System.exit(0); } Interfaces and Callbacks

COMP201 Topic 6 / Slide 22 Interfaces/Outline l Outline n Interface basics –Introduction –Defining interfaces –Using interfaces n Interfaces vs abstract classes n Callbacks via interfaces: common use of interfaces n The Cloneable Interface: a special interface

COMP201 Topic 6 / Slide 23 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. (Deep copy) l In order to clone objects of a class, you must have the class have the class implements the Cloneable interface redefine the clone method change its access modifier to public. Example: CloneTest.java n The next several slides are based on this example The Cloneable Interface

COMP201 Topic 6 / Slide 24 l What is the purpose of these rules? n Cloning is tricky. This is to reduce programming mistakes l How the rules are enforced by java? Object has clone method. All other classes are subclasses of Object. n So they all inherit the clone method. Why MUST the clone method be redefined, change to public, and the class must implement the Cloneable interface? The Cloneable Interface

COMP201 Topic 6 / Slide 25 Cloning is tricky Default implementation of the clone() method of Object n Copies bit-by-bit. n Ok for copying objects whose fields are primitive types n Not ok for cloning objects with reference fields.

COMP201 Topic 6 / Slide 26 Cloning is tricky clone method of Object does shallow copying. l Employee original = new Employee("John Q. Public", 50000); original.setPayDay(2003, 10, 1); Employee copy = original.clone(); payDay not copied! What would happen if copy was paid 30 days earlier? copy.payDay.addPayDay(-30); But this also affects original.hireDay! Actually compiler error. But let’s assume it is alright for now John original copy … John CloneTest1.java

COMP201 Topic 6 / Slide 27 How is the problem solved? l Suppose we want to clone Employee. public class Employee implements Cloneable { … public Object clone() { try { // call Object.clone() Employee copy = (Employee)super.clone(); // clone mutable fields copy.payDay=(GregorianCalendar)payDay.clone(); return copy; } catch (CloneNotSupportedException e) {return null;} } CloneTest.java

COMP201 Topic 6 / Slide 28 How is the problem solved? l Employee original = new Employee("John Q. Public", 50000); original.setPayDay(2000, 1, 1); Employee copy = original.clone(); payDay copied! What would happen if copy was paid 14 days earlier? copy.payDay.addPayDay(-30); This has NO affects original.payDay! originalcopy … … John John

COMP201 Topic 6 / Slide 29 l What is the purpose of these rules? n Cloning is tricky. This is to reduce programming mistakes l How the rules are enforced by java? n Object has clone method. n All other classes are subclasses of Object. n So they all inherit the clone method. n Why MUST the clone method be redefined, change to public, and the class must implement the Cloneable interface? The Cloneable Interface

COMP201 Topic 6 / Slide 30 How are the rules enforced? l Protected access revisited: protected fields/methods can be accessed by classes in the same package. n Example: package Greek; public class Alpha { protected int iamprotected; protected void protectedMethod() {…} } package Greek; class Gamma { void accessMethod() { Alpha a = new Alpha(); a.iamprotected = 10; // legal a.protectedMethod(); // legal }}

COMP201 Topic 6 / Slide 31 protected fields/methods can also be accessed by subclasses l However: A subclass in a different package can only access protected fields and methods on objects of that subclass (and it’s subclasses) package Latin; import Greek.*; class Delta extends Alpha { void accessMethod(Alpha a, Delta d) { d.iamprotected = 10; // legal d.protectedMethod(); // legal a.iamprotected = 10; // illegal a.protectedMethod(); // illegal } How are the rules enforced?

COMP201 Topic 6 / Slide 32 How are the rules enforced? How does java disallow calling the clone method of Object to clone an Employee ? The clone method of Object is protected. CloneTest not in the same package as Object. Hence cannot call the clone method of Object to clone an Employee. –In CloneTest, one can only clone objects of CloneTest n Must override before use –If not, we get compiler error “clone() has protected access in java.lang.Object Employee copy = (Employee)original.clone();” ^

COMP201 Topic 6 / Slide 33 Can we refine the clone method, but do not implement the Cloneable interface? class Employee //implements Cloneable { public Object clone() {…} } No. The clone method throws CloneNotSupportedException at runtime if called on objects whose class does not implement the Cloneable interface. All Arrays implement the Cloneable iterface How is the mechanism enforced?

COMP201 Topic 6 / Slide 34 Consequences Redefinition of clone method is necessary even when the default is good enough. l Compiler does not any idea whether the default is good enough. class Person implements Cloneable { … public Object clone() { try { return super.clone(); } catch (CloneNotSupportedException e) { return null; } //This won’t happen, since we are Cloneable }

COMP201 Topic 6 / Slide 35 Tagging Interface What are the methods in Cloneable ? The clone method is inherited from class Object. It is not a method of the Cloneable interface. The Cloneable interface has no methods and hence called a tagging interface. Technically, it prevents the clone method to throw CloneNotSupportedException at runtime. For programmers, it indicates that the class designer understand the clone process and can decide correctly whether to refine the clone method. The Serializable interface is another tagging interface.

COMP201 Topic 6 / Slide 36 Inner Classes/Outline l Introduction l Inner classes through an example l Local inner classes l Anonymous Inner classes l Static inner classes

COMP201 Topic 6 / Slide 37 Introduction to Inner Classes l An inner class is a class defined inside another class l Similar to nested classes in C++, but more flexible & more powerful. l 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.

COMP201 Topic 6 / Slide 38 Inner Classes Through An Example Task: Write a program that adds interest to a bank account periodically. Following the TimerTest example, we write public class AddInterest { public static void main(String[] args) { // construct a bank account with initial balance of $10,000 BankAccount account = new BankAccount(10000); // construct listerner object to accumulate interest at 10% ActionListener adder = new InterestAdder(10, account); // construct timer that call listener every second Timer t = new Timer(1000, adder); t.start(); … // termination facility } } // AddInterest.java

class InterestAdder implements ActionListener ….//print out current balance { public InterestAdder(double aRate, BankAccount aAccount) { rate = aRate; account = aAccount; } public void actionPerformed(ActionEvent event) { // update interest double interest = account.getBalance() * rate/ 100; account.setBalance( account.getBalance()+interest); } private BankAccount account; private double rate; } Note that InterestAdder requires BankAccount class to provide public accessor getBalance and mutator setBalance.

COMP201 Topic 6 / Slide 40 The BankAccount class class BankAccount { public BankAccount(double initialBalance) { balance = initialBalance;} public void setBalance( double balance) { this.balance = balance;} public double getBalance() { return balance;} private double balance; } Inner Classes Through An Example

COMP201 Topic 6 / Slide 41 The program AddInterest.java works l BUT, not satisfactory: BankAccount has public accessor getBalance and mutator setBalance. n Any other class can read and change the balance of an account! l Inner classes provide a better solution Make InterestAdder an inner private class of BankAccount Since inner classes can access fields and methods of outer classes, BankAccount no longer needs to provide public accessor and mutator. The inner class InterestAdder can only be used inside BankAcccount. Inner Classes Through An Example

COMP201 Topic 6 / Slide 42 class BankAccount { … private double balance; private class InterestAdder implements ActionListener { public InterestAdder(double aRate) { rate = aRate; } public void actionPerformed(ActionEvent event) { // update interest double interest = balance * rate / 100; balance += interest; …// print out current balance } private double rate; } Inner Classes Through An Example Access field of outer class directly

COMP201 Topic 6 / Slide 43 Only inner classes can be private. Regular classes always have either package or public visibility. Inner Classes Through An Example

COMP201 Topic 6 / Slide 44 InterestAdder can only be used inside BankAccount, so we need to place timer inside BankAccount also : class BankAccount { public BankAccount(double initialBalance) { balance = initialBalance;} public void start(double rate) { ActionListener adder = new InterestAdder(rate); Timer t = new Timer(1000, adder); t.start(); } … } Inner Classes Through An Example

COMP201 Topic 6 / Slide 45 l The driver class: public class InnerClassTest { public static void main(String[] args) { // construct a bank account with initial balance of $10,000 BankAccount account = new BankAccount(10000); // start accumulating interest at 10% account.start(10); JOptionPane.showMessageDialog(null,"Quit program?"); System.exit(0); } } //InnerClassTest.java Inner Classes Through An Example

COMP201 Topic 6 / Slide 46 Inner Classes/Outline l Introduction l Inner classes through an example l Local inner classes l Anonymous Inner classes l Static inner classes

COMP201 Topic 6 / Slide 47 Local Inner Classes l Note that in BankAccount class: The class InterestAdder is used only once in method start. In this case, Java lets you define class InterestAdder locally inside method start.

COMP201 Topic 6 / Slide 48 Local Inner Classes public void start(double rate) { class InterestAdder implements ActionListener { public InterestAdder(double aRate) { rate = aRate; } public void actionPerformed(ActionEvent event) { double interest = balance * rate / 100; balance += interest; …// print out current balance } private double rate; } ActionListener adder = new InterestAdder(rate); Timer t = new Timer(1000, adder); t.start(); }

COMP201 Topic 6 / Slide 49 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. It can access local variables if there are final. Local Inner Classes

COMP201 Topic 6 / Slide 50 Local Inner Classes public void start( final double rate) { class InterestAdder implements ActionListener { // no constructor now needed in this case public void actionPerformed(ActionEvent event) { double interest = balance * rate / 100; balance += interest; …// print out current balance } // the rate field is gone. } ActionListener adder = new InterestAdder(); Timer t = new Timer(1000, adder); t.start(); }

COMP201 Topic 6 / Slide 51 Inner Classes/Outline l Introduction l Inner classes through an example l Local inner classes l Anonymous Inner classes l Static inner classes

COMP201 Topic 6 / Slide 52 Anonymous Inner Classes l Anonymous inner classes take this one step further. Kind of replacing the usage of InterestAdder with its definition. public void start( final double rate) { ActionListener adder = new ActionListener() { public void actionPerformed(ActionEvent event) { double interest = balance * rate / 100; balance += interest; … // print out current balance } Timer t = new Timer(1000, adder); t.start(); } // AnonymousInnerClassTest.java

COMP201 Topic 6 / Slide 53 Analogy X=A+B+10; Y=X Substitution: Y=A+B+10;

COMP201 Topic 6 / Slide 54 l General syntax: new someInterface() {…} creates an object of an anonymous inner class that implements someInterface new someClass( constructionParameters){…} creates an object of an anonymous inner class that extends someClass. l 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. Anonymous Inner Classes

COMP201 Topic 6 / Slide 55 Inner Classes/Outline l Introduction l Inner classes through an example l Local inner classes l Anonymous Inner classes l Static inner classes

COMP201 Topic 6 / Slide 56 Static Inner Classes l Static inner classes are inner classes that do not have reference to outer class object. class ArrayAlg { public static class Pair { public Pair(double f, double s) { … } public double getFirst(){ … } public double getSecond(){ … } 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++

COMP201 Topic 6 / Slide 57 Static Inner Classes l Static inner classes can be used to avoid name clashes. For example, the Pair class in our example is known to the outside as ArrayAlg.Pair. Avoid clashing with a Pair class that is defined elsewhere and has different contents, e.g. a pair of strings. StaticInnerClassTest.java