In-class notes for 01/05/2018
CS 284 (MCA), Interim 2018
Lab assignment due at "midnight"
This session: Lab 3: Interfaces and Adapters
First quiz today at 1pm, on Java coding and concepts (through Lab2). Topics
Submitted questions on assignments and technology
Submitted questions on graphics reading
Event-driven programming
In event-driven programming, a programmer writes code that specifies how a program should respond to events that typically originate outside of that program. This is the usual approach for writing user-interface code, since a user's interaction and system activities ordinarily initiate program actions (e.g., through a button click, text entry, or from a network communication). These interactions and activities are called events, and the code for responding to a particular event is called a callback or event handler.
A Java interface is a specification of methods required for a particular type of event callback. For example, the interface
ActionListener
indicates the method used for button-click callbacks, calledactionPerformed()
public interface ActionListener extends EventListener { void actionPerformed(ActionEvent e); }
This interface is predefined in the packagejava.awt.event
. Note that the methodactionPerformed()
is declared in the interface, but not defined there -- i.e., no code is provided for the method here. In order to respond to button clicks, a program must provide an implementation ofactionPerformed()
appropriate for that particular program and button. This is called implementing the interface.Walkthrough of
~cs284/java/Scribble.java
Callback code
Creating components (e.g., button)
Registering callbacks with event sources. This arranges for those callbacks to be called when those events occur.
Placing components into the (Applet) container
An object that implements a callback is called an adapter in Java.
Adapter styles
Java provides several ways to implement callback methods in classes of a program. See
~cs284/java/adapters
Adding the callback methods to the Applet itself
Self.java
;Using Inner classes
Inner.java
orInner2.java
(with variables for the adapters);Adding callbacks in a subclass
Subclass.java
;Anonymous classes
Anonymous.java
.Lambda in Java
adapters/Lambda.java
extends
), but they can implement any number of interfaces. Interfaces provide many of the advantages of subclassing. For example, any instance of a class that implements interfaceX
can be passed as an argument of typeX
for in a method (e.g.,addActionListener
)."Camel capitalization"
< >