Java Exam Prep < 2
marks = four sentences >
Level
2 html introduced forms. With server-side CGI technology, it revolutionised the
web.
Helper
applications:
Suffix in file name indicates data type. Rather than browser being bloated with
every possible type of data, browser copies the data file to the local disk
then launches a helper application to read and process the file. Server sends
details of the MIME (= Multiple Internet Mail Extension) type of data as part
of the header. Eg: .wav, .gif, .au.
Plug
ins:
Browser provides functions that can be used by extension code to get config
info for data the browser is not equipped to handle. Plug ins can be
dynamically linked when extension code doesnt have to be part of the
browser. Plug ins must be native (machine) code, compiled to run on a
particular platform, = are not platform independent, so users must get the
appropriate plug in for their system.
Image
maps:
Client side image maps now, eg.
Method:
Name:
Action:
OnSubmit ΰ data is encoded and sent to web server, new
process forks off, program reads data, sends ???
back to client.
Radio buttons: choose 1 of many.
Checkbox = 2 state, on/off,
true/false.
Text:
TextField text = new TextField(20,
"Enter your name"); // CREATE empty textfield with default width
TextArea text = new
TextArea("Type here", 10, 40); // where numbers are R, C sizes.
Use add(TextField); or
add(TextArea); // ADD textfield to an applet (always Create before Add !!)
Use setText and getText methods.
Use text.setEchoChar('*'); for
passwords.
Select:
Submit:
Choice: A large set of radio
button that displays as a popup list can select only one. [ 1Choice. ]
List: A variation of Choice.
Allows multiple selections, in a scrollable window. [ List-has-many. ]
Label: Neither Choice nor List
displays a label, so you can add a non-editable string using Label.
public void init() {
Label label = new Label
("Hello");
add(label); }
OR: add(new
Label("Hello"));
>>>> Review lecture notes to give NG what he wants.
JS
is a scripting language, not a programming language. For developing client and
server applications.
Typeless: No??. Its code
switches between text and numerics. A little sloppy about variable declarations
(JS is weakly-typed.) You can define a variable
and the runtime system will check whether the requested operations are
appropriate to the data type. As it is typeless,
there is no return type.
"Variable
data types not declared (loose typing)". "JS is a loosely typed
language. You dont have to declare a data type of a variable. Data types are
converted automatically with JS statements."
"If
data types and variables are not declared, JS is dynamically typed."
Event
driven: No,
JS is not an event handling system. But most JS code specifies functions to be
called when events occur. Mostly these are user events that trigger
Just-in-time ?compilation.
"Most
JS functions are called in association with an event for an element involving something
on a HTML page." (NG)
"JS
is able to respond to events on a web page these features are called event
handlers. Eg onMouseover, onLoad event handlers."
"JS applications in Navigator are largely event-driven. Events are actions that occur, usually as a result of something a user does. Event handlers = scripts that are automatically executed when an event occurs. They are embedded in documents as attributes of HTML tags." (JS book).
Event
driven (Harrington,
Java book p167) = GUI programs are event driven which means they wait for
something to happen, identify what has happened, and act based on what
happened. Events include mouse movements, clicks, menu choices, etc. (A true
event driven program responds to more than a menu choice that uses a switch construct.)
Event driven programs therefore require event listeners. These must be attached
to the objects they want to listen to.
By this definition, JS is not
a true event driven program.
Object
oriented: No.
JS is "object-based" (correct term) (Book also calls it "an
object oriented script language", p.81) to a limited extent but it
lacks true classes in the OOP sense "its code uses built-in
extensible objects but has no classes or inheritance". You can define data
types and functions and tell data objects to act. But mainly JS uses objects
provided by the browser (eg, that provide info about the browser, window, current
page, forms, date, etc).
JS
is used to validate form data on the client side, put a comment in the browser
status bar, calculate,
..
By
placing function calls inside the tag. Eg, onLoad, onUnload,
onBlur, onFocus, onMouseOver, onSubmit, onSelect, onChange,
Function
definitions and global variables go inside the tags this code is
executed as the page loads.
In
the body of the page, you put the event-related calls to functions.
>>>Check NG notes, because book says:
"JS
can be embedded in an HTML document in one of 2 ways: as statements and
functions using the SCRIPT tag, or as event handlers using HTML tags
Functions
are executed by events in the page. Define the functions (using the SCRIPT tag)
in the HEAD. This guarantees that functions are loaded before the user has a
chance to do anything that might call them." Book, p.66-9.
Web
and http are mostly stateless, ie no memory. But cookies provide memory an
alternative to expensive database. Persistent client state http cookies.
Cookies = text records of URL and name value pairs, stored (unencrypted) on
client browser. When this URL page is fetched next, cookie's name value pairs
accompany the request and a new page is dynamically generated (by the CGI
program).
Promiscuous: Hacker can have a machine
listening to broadcasts of network traffic. How? He sets the interface on his
machine to promiscuous mode, so it filters all packets looking for specified
address headers. Can pick up passwords if he sets filters to look for sequences
that start telnet, ftp, login sessions.
Sniff: In a non-switched network,
Ethernet frames broadcast to all machines on the network, but only the computer
that the packets are destined for will respond. All of the other machines on
that network still see the packet, but if they are not the intended receiver,
they will disregard it. When a computer is running sniffer software and its
network interface is in promiscuous mode (where it listens for ALL traffic),
then the computer has the ability to view all of the packets crossing the
network.
Sniffers
= network traffic analyzers. Crackers install sniffers to obtain usernames,
passwords, credit card numbers, personal information, etc.
Spoofing: Is harder. Have to change DNS
tables or router tables, so hacker machine looks like either a local machine
(where password may not be required) on your network or a server.
Ethernet
= local area network it sends data by packets.
Spoof = to capture, alter, and
retransmit a communication stream in a way that misleads the recipient. As used
by hackers, refers especially to altering TCP/IP packet source addresses or
other packet-header data in order to masquerade as a trusted machine. To spoof
an IP address, that means that in the header of the packet, you are changing
the source address as to conceal the real source address.
A
checksum adds up the value of bytes, does a modulo, and sends the result with
the message.
A
message digest is more complex, sensitive (128 bit often) it combines data
from each character
To
help detect if data has changed in subtle ways, eg $109 to $190.
Public-private
key pairs: Most encryption systems use the same key for encrypt and
decrypt called symmetric. Called DES. But can have 2 keys asymmetric. You
publish your public key for anyone to use if they want to send you a message.
Inputs into the encryption algorithm are your public key + their message.
Result is garbled text. You use the same encryption algorithm with your private
key + garbled text to decode the message. Safe but slow. Thus:
To
confirm I'm talking with Joan, we swap our agreed text string it's encoded
using her private key. I decode it with her public key. If it's right, it's
her.
To
be even more sure, a certification company can confirm the name, address
and public key of my correspondent. 3 levels of service: his entry in their
database, that entry was confirmed, Verisign phoned him.
Secure
language:
Examples
of Java being a secure language:
Array
bounds checks attempts to overrun a buffer will result in runtime exception.
No
direct manipulation of pointers
Type
case verification by compiler
Access
to member functions checked by compiler.
Also
ClassLoader it's a supplied class that defines operations needed to resolve a
class being loaded it keeps track of the source of classes by keeping the
newly loaded classes separate from java.* classes.
[java.security provides a means to examine a
class at loadtime, to determine its level of access to the local system. With
Java you can fix the openings for hacking in.]
Sandbox
execution environment: Is a very limited environment in which applets run, with no access to
theselocal system files; execution of local commands; any socket connection
(except the originating URL that loaded the applet note: a new TCP/IP
connection is opened to the server to ask for byte codes of the compiled Java
program when the code is loaded, the byte array is passed to the JVM for
execution); any GUI resources not managed by the browser; Also, windows open by
the browser on behalf of the applet are tagged as "Untrusted".
With
applets and applications, a SecurityManager class is used to determine access
characteristics asks: is he allowed to write to that? [Applications are
considered trusted.]
Code
signing:
"digital signing, which allows you to unequivocally know everyone
that wrote all the programs that have special access to your system"
relevant??
2tier: Client machine has (B)
Java app + JDBC --- connects through DBMS-proprietary protocol to --- (C) DBMS
database server. "In the 2 tier model, a Java applet or application talks
directly to the data base. This requires a JDBC driver that can communicate
with the particular database management system being accessed. A user's SQL
statements are delivered to the dbase and the results are sent back to the
user."
3tier: (A) Java applet or HTML
browser on client machine --- connects through HTTP, RMI or CORBA (= Common
Object Request Broker Architecture) calls to --- (B) Application server (Java)
+ JDBC --- to --- (C). "In the 3 tier model, commands are sent to a middle
tier of services which then send the SQL statements to the dbase. It processes
them and sends results back to the middle tier which sends them on to the
user." Benefits of 3 tier: MIS managers can maintain control over access;
can use higher level API (with its GUIs on the clients); often performance
advantages with 3tier.
JDBC
is a low-level interface so it invokes SQL commands directly. Thus JDBC is the
base for higher level interfaces and tools that are user-friendly.
DriverManager:
Keeps track of available drivers, makes and manages connections.
Connection:
Represents a session with a database. Events are: establish connection, pass
SQL statements to database
Statement:
Sends simple SQL statements. Also available are PreparedStatement (is
pre-compiled), CallableStatement (to execute a stored SQL procedure).
ResultSet:
Contains the rows that satisfy the query conditions like an Iterator, it uses
next().
Connection
dbx = driverManager.getConnection (db_URL, myuserID, myPassword);
Statement
stmt = dbx.createStatement();
String
query = "SELECT Name, Address FROM CustomerTable WHERE
";
ResultSet
results = stmt.executeQuery(query);
While
(results.next()) {
String custName = results.getString
("Name");
}
RMI: Is object oriented
communication, Java to Java. There's no need to invent protocol use
standard mechanisms for passing arguments for method calls.
Ports
and sockets:
Java client can communicate with servers written in other languages, BUT programmer
must devise an application specific protocol defining how the
data are sent. Java to other languages. (Socket = a software abstraction
for a medium of network communication; it connects a stream of network data to
a java program.)
"Java
1.1 includes the Java Beans standard, which is a way to create components that
can be used in visual programming environments. This promotes visual components
that can be used under all vendors development environments. Since you arent
tied to a particular vendors design for visual components, this should result
in greater selection and availability of components. In addition, the design for
Java Beans is simpler for programmers to understand; vendor-specific component
frameworks tend to involve a steeper learning curve."
What: Beans API = (1) mainly interfaces (BeanInfo, Customizer,
PropertyEditor, PropertyChangeListener, VetoChangeListener). Serializable is
not in Beans API but is an important interface which all beans must
implement. And (2) and a few classes to provide support structure (Beans,
Introspector, PropertyEditorManager) and about the individual beans
(BeanDescriptor, etc).
Builder tool =
Why:
Extends allows for single not
multiple inheritance. "Java uses a singly-rooted hierarchy, so all objects
are ultimately inherited from the root class Object."
Eg. class Alien extends Object
"Java
uses the extends keyword to indicate inheritance from a base class and
the super keyword to specify methods to be called in the base class that
have the same name as the method youre in."
Parent
= super class. A subclass can only extend one superclass.
Interfaces have no implementation. interface
is just an interface (has no data members, no definitions, it just captures
some general functionality) contrast extends, which extends existing
functionality. To create a version of the interface that can be
instantiated, use the implements keyword:
public interface Face {
public void smile();
}
public class Baz extends Bar implements Face {
public void smile( ) {
System.out.println("a warm smile");
}
}
The
interface keyword takes care of combining multiple interfaces.
Seems to me that an object can have the qualities/methods/? of various other classes/?objects, thus you can interface with several other ?classes (objects). Right?? Word it better??
Because
any input operation can fail, bracket them in try{} catch{} exception handling
code.
Exception
= situation that could crash the program. ?or corrupt the results.
Eg
RuntimeException class when trying to access an out of bounds array index.
In
Java, specifying is not optional. If a member function can throw an
exception, this must be stated in the declaration. Eg:
Class
Integer
{
public static int parseInt (String
s) throws NumberFormatException
}
"Exception handling in
Java is different because there are no destructors. A finally clause can be
added to force execution of statements that perform necessary cleanup. All
exceptions in Java are inherited from the base class Throwable, so
youre guaranteed a common interface. Main subclasses are IOException and
RuntimeException.
public void f(Obj b) throws IOException {
myresource mr = b.createResource();
try {
mr.UseResource();
} catch (MyException e) {
// handle my exception
} catch (Throwable e) {
// handle all other exceptions
} finally {
mr.dispose(); // special cleanup
}
}"
The
base class for all exceptions is Throwable, which has 2 types (Exception and
Error). Relevant?
Can
add a throws clause to any method declaration to indicate that it can throw an
exception,
eg: public void Foo ( )
throws Exception1,
Exception2, Exception3 // could be more in the list.
{
}
Then
you create a new object of the type of the required exception class, using the
keyword throw to deliver it:
throw new IOException ("Bad
file name");
Catching
it: try {
// code that we're
testing }
Catch (MyExceptionClass
e) {
// exception handler code }
May
also optionally add a finally block that does not depend on there being an
error or not, eg:
finally
{
try
{ f.close( ); }
catch
(IOException e)
{
System.err.println
"Exception closing file" + e);
return;
}
}
{
Object-oriented. Object = data + methods
(procedures) that act on that data. Are encapsulated.
Robust: "Generally, Java is
more robust, via:
Object handles initialized to null (a keyword)
Handles are always checked and exceptions are thrown
for failures
All array accesses are checked for bounds violations
Automatic garbage collection prevents memory leaks
Clean, relatively fool-proof exception handling
Simple language support for multithreading
Bytecode verification of network applets"
Architecture
neutral:
Because it's based on the bytecode-interpreter model where each machine has its
own unique interpreter that interprets the bytecode into code readable by that
particular machine. "Bytecode is easy to interpret on any machine, and
easily translated into native machine code at load time."
Portable: Cf native. [ =?Platform
independent because it compiles source code files into (?byte) code files that
JVM can decode. The JVM is a platform-specific byte code interpreter it
translates byte code into native instructions on the host computer that can be
executed on that computing platform. Byte code is executable and has a .class
file extension.] Java specifies number
ranges to ensure portability.
.java
ΰ |
COMPILER
ΰ |
.class
ΰ |
INTERPRETER |
ΰ Native code |
Source
code (a text file written in Java programming language using NotePad etc)
with a .java extension
|
is
compiled (if there are no errors) into
|
executable
generic binary bytecode (named after the class with a .class file extension)
that is executed/run by
[bytes
of code are instructions in machine language to a virtual (unreal)
microprocessor called JVM] |
the
web browser's built-in Java interpreter
[
This requires the machine to have JVM installed ] |
which
produces native code (ie. This new button looks like every other button on
your system). |
.java |
Called
javac. |
.class |
Called
java.exe |
|
ό
In
C++, source code is Compiled into object (.o) files, then these
are Linked with libraries to get an Executable, then Run.
Memory: COLER.
ό
In
Java, all details of class are in one file (= a single syntactic unit that
contains the definitions of all member functions), ie no separate header
file as in C++.
Compilation: Javac (=compiler) compiles
the source code (text files) into executable Java programs (= bytecode) with
.class file extensions that are generic.
When
you compile in Java, you dont generate instructions for one specific machine
you generate bytecode which is instructions for the JVM, so your compiled
program will run on any machine on any platform that has its own JVM.
Linking: Java loads code for classes when it needs to there is no link
step.
Execution: Starts with the main()
method of the driver class (which has the same name as the source file).
Step
1. Create the source file, eg. MyProgram.java This is text
written in the Java programming language.
Step
2. Compile it with the javac compiler into a bytecode file. javac
MyProgram.java The compiler javac translates it into bytecode, =
instructions that the JVM can understand
Step
3. Run the bytecode progam on my computer. If it's an application, run
it with java -- if it's an applet, run it with appletviewer or your web browser
(eg. Netscape). java myProgram
Each computing platform has its own version of an interpreter, ie. Win32
is different to MacOS or Solaris. The Java interpreter on my computer loads and
runs the .class files, ?= it "implements the JVM", = translates into
instructions that my computer can understand.
Package = collection of classes and
interfaces that in some way belong together, and whose instances often
interact. An organisational unit that is greater than a single file. Eg:
java.math, java.io, java.awt
Over
50 packages.
Namespace: Java offers a
"universe of classes", a systematic way of uniquely naming every
class invented by any Java programmer on the network. Similar control in C++ is
through namespace.
"Java
uses packages in place of namespaces. The name issue is taken care of by
putting everything into a class and by using a facility called
"packages" that performs the equivalent namespace breakup for class
names. Packages also collect library components under a single library name.
You simply import a package and the compiler takes care of the
rest."
"
Java packaging provides the equivalence of namespaces, so that isnt an issue.
Java 1.1 has inner classes that look just like nested classes. However,
an object of an inner class secretly keeps a handle to the object of the outer
class that was involved in the creation of the inner class object. This means
that the inner class object may access members of the outer class object
without qualification, as if those members belonged directly to the inner class
object."
Access
control:
Similar to friend in C++. C++ has class, subclasses, clients, friends. Java has
class, other classes in same package, subclasses in same package, other
subclasses, clients.
??Relevant:
" Instead of controlling blocks of declarations like C++ does, the access
specifiers (public, private, and protected) are placed on
each definition for each member of a class. Without an explicit access
specifier, the default for that element is "friendly," which
means that it is accessible to other elements in the same package (equivalent
to them all being C++ friends) but inaccessible outside the package. The
class, and each method within the class, has an access specifier to determine
whether its visible outside the file."
From most to least restrictive, it's private
(only accessible to its own class/the defining package), default (accessible to
whole package), protected (accessible to subclasses too), public (no
restriction on which classes can access it).
Object
reference variables contain either null or the address of the object created by
new (= the address returned by the new operator).
Advantage: ?? Dont have to specify the size of an array before you start. More?
Disadvantage: Java's object reference
variables can't be used in calculations only to access objects.
Advantages:
C++
classes have destructors to free up resources (most commonly memory but also
sockets).
Java
has automated garbage collection so you dont have to explicitly free memory by
using destructors.
Java
has finalize() which serves similar role to destructor but no guarantee when
it will be done so can't rely on it. Instead put your resource release code in
a method you define, eg: tidy_up(), dispose() or destroy().
Disadvantages:
Collection
class =
Eg: dictionary, stack, hashtable,
vector.
Vector: = A general purpose
resizable array class that is very useful when working with collections of
objects. It handles all the details of adding and removing elements from
arrays, and tries to use memory efficiently. It is a type safe dynamic
collection class, therefore efficient memory management. Is a list of items,
more powerful than an array, can grow in size dynamically.
"Java
has no templates or other implementation of parameterized types. There is a set
of collections: Vector, Stack, and Hashtable that hold Object
references, and through which you can satisfy your collection needs, but these
collections are not designed for efficiency like the C++ Standard Template
Library (STL). The new collections in Java 1.2 are more complete, but still
dont have the same kind of efficiency as template implementations would
allow." (book)
How? "In order to be used
in a vector, simple data types (ie, boolean, char, double, float, int, long)
need to be converted to objects using the java.lang wrapper classes."
Because you can only store objects in a vector.
Vectors
are allocated as objects using the new operator: Vector theVector = new
Vector();
Vector
is a resizable one-dimensional array. Because it's an object, manipulation
requires using class methods.
Advantages: Flexibility; control you
can move elements; can add/delete/insert on the fly. Efficient no allocated
but unused memory.
Disadvantages: Each access requires a
method call; slower needs array creation and data recopying each time.
Thread
class is in java.lang package, has basic thread operations (start, yield, kill,
priorities)
(You
create a thread object then call its start() method.)
Use
a Runnable interface (ie, thread object + runnable object) { runnable
provides run() ?? }
Use
synchronized qualifier for methods every object has a lock these put locks
on objects; you have exclusive control while you're in a block of code.
Use
wait() and notify() operations defined at Object.
Eg:
You want to gain control of anyObject
Synchronized (anyObject) {
// the code involving
anyObject
}
The
above code blocks until anyObject is not locked, locks anyObject, does the
code, releases the lock.
There's
a better way (less likely to make errors): Make synchronization part of the
signature, eg:
Public
final synchronized void anyClass (parameters, if any) {
}
"Theres
a Thread class that you inherit to create a new thread (you override the
run( ) method).
Mutual
exclusion occurs at the level of objects using the synchronized keyword
as a type qualifier for methods. Only one thread may use a synchronized
method of a particular object at any one time. Put another way, when a synchronized
method is entered, it first "locks" the object against any other synchronized
method using that object and "unlocks" the object only upon exiting
the method.
There
are no explicit locks; they happen automatically.
Youre
still responsible for implementing more sophisticated synchronization between
threads by creating your own "monitor" class.
Recursive
synchronized methods work correctly. "Synchronization lock is a
form of ??recursive mutex" (NG)
Time
slicing is not guaranteed between equal priority threads." (book)
To
prevent multithread access conflicts:
"
The simplest method is to make your variables private (but you do that
already, right?) and to use synchronized accessor methods. Accessor
methods allow access to private member variables, but in a controlled
manner."
Unicode
characters = unsigned 16bit (not 8bit), thus value range of 0-65,536.
To
be able to represent all human languages in a platform-independent and portable
way.
Standardized
definitions of int (it's always 32bits, on all platforms) thus Java is
robust, safe and cross-platform portable.
Use
the keyword/qualifier final.
Classes,
member functions, variables can all be final but can
methods?? (I think so)
In
Java, public and protected functions can be overridden if not specified as
final; private functions can never be overridden.
Static
= this member exists once per class (not per instance of the class).
Static
has same meaning as in C++:
STatic data member = shared by all inSTances
of the class.
Static member function (method) = has no data members
(or only uses static data members).
Sometimes
a class requires some type of initialisation before it is ready to create
objects. Here Java allows you to declare a static block. This is code that gets
executed when a class is first loaded. Thus it is executed before the class can
be used for any purpose, eg. before any objects are constructed. This is useful
when you want to create constant data that is useful to all the instances and
subclasses of a class. Eg myBook p253. Eg:
class User {
static String userList[] = new String[3]; // note
use of static keyword
static {
userList[0] = "Ed";
userList[1] = "Fred";
userList[2] = "Joe";
System.out.prinln("Users loaded and
initialised."); ί this line optional.
}
}
Transient
denotes that a field in a class object will not be persistent through
serialisation. The value of a transient variable need not persist when an
object is stored. A transient field is one that does not affect the state of an
object.
The
transient qualifier says 'dont try to save this object, it has a link to a collaborator'
(= ???).
Keyword
transient is added along with private/protected/static/etc.
Example
of use: you wouldnt want to save the state of the Canvas object during
continual repainting, so make it transient.
How
to use: Define the class as one that implements Serializable, then use
transient type qualifier for any references that are not 'state' data and which
are not to be saved.
Prior
to execution, it checks
ό
Variable
initialisation
ό
Scope
are all accesses to local variables within scope of the expected stack frame?
ό
Size
nothing too large created on stack?
ό
Matching
do the operations invoked on objects match their class signatures and
accessibilities?
A
stack is a FILO (first-in last-out) list. Like a stack of plates. MyBook p 187
A
stack is a subclass of Vector which implements a LIFO stack. Naughton p206
Native
= of the platform it's running on. Delivered by Swing library in Java 2.
The
objectives of AWT is "write once, run anywhere" (= platform
independent code) and to support the look and feel of each platform.
java.awt.peer defines a set of interfaces.
AWT
is a thin software layer that gives access to the system's API (application
programming interface). Peer classes = the underlying classes that provide
specific windowing functions. If AWT creates a button on a Mac, it's a Mac
button peer classes give it the look and feel of their host op sys. Button
has an intermediary (proxy) that does the work.
In contrast to API components, Swing
components work the same on all platforms. Memory: Same Swing!
Layout
managers are used to arrange positioning of subwindows.
How
used: setLayout(Layout Manager m)
add(Component c)
or- add(Component c, constraints)
Example
1: A Frame with a FlowLayout manager will display components left to right
across the page, creating a second/etc row if necessary. FlowLayout class is
the default.
Example
2: BorderLayout specifies region names, eg West, center, etc.
Example
3: GridLayout.
Eg: setLayout(new GridLayout(2,2)); // creates 2x2
table.
There
are 2 strategies for handling events: 1. old and widely used, 2. new.
1. How
chain of command pattern worked: event (eg keystroke, mouse action, menu
choice) is reported to series of "next handlers" until it reaches an
object that deals with it.
Why
it was replaced: Inefficient (lots of processing), restrictive (event handlers must be
components).
2.
Dependency (Observer) pattern. Listeners/dependents/observers register an
interest. If an object is changed, all its dependents are notified and updated
automatically, eg: addActionListener(ActionListener 1)
Different
types of listeners interested in different types of events, eg: the
AdjustmentEvents interface, the MouseListener interface (doesnt track motion),
the MouseMotionListener interface, the ActionListener interface
[[
An interface defines the general characteristics that are shared among multiple
classes, = a group of public methods that can be implemented and then used as
the basis for interacting with an object; it has unimplemented methods only.
Relevant??
Interface
is more abstract, has no data members, no definitions whereas abstract class
can have data members, can have member functions defined. Interface class has only
un-implemented methods abstract class can have implemented methods and member
variables.
Abstract
keyword now only = "partially implemented abstract class".
Because
interfaces are not full blown classes, you dont extend them you implement
them. Relevant?
Cf.
abstract data types are partially implemented (eg. Regions in Ass2), can also
have implemented methods and member variables. ]]
"When a Java program needs to redraw an object on the screen, it eventually calls the object's paint method, which is the only location for drawing text or graphics. The method takes a single object of the Graphics class as a parameter. The Graphics class, from which your program never creates objects directly, acts as a base class for all graphic elements. The graphic element being painted is therefore typecast to a Graphics object. All calls to methods that draw text or graphics shapes do so using this object." (Book, Harrington p201).
"Whenever
the applet must redraw its output, paint() is called. The paint() method has
one parameter of type Graphics. This parameter will contain the graphics
content, which describes the graphics environment in which the applet is
running." (my book, p478).
User
event ΰ message ΰ op sys (event manager) ΰ message ΰ application code (event
handler).
Graphics
programming is by means of a set of packages called JFC (Java Foundation
Classes) including AWT (for GUIs), Swing
java.awt.Component
has buttons, menus, scroll bars, etc these are all Components (= controls).
Graphics
system have red, green and blue values for each pixels, plus transparency. The
"transparency" is the "alpha channel" of a pixel.
Images
are loaded
ImageObserver keeps track of images as
they are loading, gets called regularly as data arrive, then (eg.) repaints a
bit at a time.
MediaTrackers: ? If you want to delay painting till a picture or group of
pictures is fully loaded, use a MediaTracker object. So create a MediaTracker
object to work with the ImageObserver object that is loading, and give it a
reference to each image that it is to monitor, then tell MediaTracker to delay
until specified image/s has arrived.
Continuous
motion requires 24 repaints per second and small motions. For a flicker free
display of graphics, use double buffering ie, create a new off screen buffer.
Draw to a memory image map, then copy cleanly to the screen.
Vector
is dynamic, so several methods could be each trying to modify the Vector at the
same time, eg one wants to add an element, another to delete one. By using
sync, the first sync method to access the vector gets to lock it; other waits
till first has completed task and releases its lock. Other threads trying to
call an in-use synchronised object will enter a wait state. When a thread
leaves a synchronised method, the object is unlocked.
Atomic: see B13, pg.8.
Isolation:
?? Basic idea is that when a
thread is operating on an object, it blocks access by other threads. Those
other threads wait.
Wait()
and notify() are final methods of Object and they can only be called from
inside synchronized methods.
wait(): #Tells the current
thread to sleep until another thread notifies it.
A
thread that owns a lock on an object can wait on that object the thread is
blocked (waiting for this object to change), then lock is released. Wait can
have a time in (). Format: while(! a_condition) wait ()
notify(): #Wakes up the first
thread that called wait on this object. A thread that owns the lock on an
object can notify of changes. "Allows another thread waiting on the object
to resume." (NG)
notifyAll(): #Wakes up all the
threads that call wait on that object the highest priority thread then runs
first.
Provide code that illustrates the use of
these constructs in the solution of a typical scheduling problem. (2 marks)
Eg:
printer controller (printer runs at constant speed, input is in bursts).
Applet
is contained in a webpage, runs on any java-compatible browser.
What
for:
data is used in name/value pairs to specify colours, text values,
. Both name and values are strings.
Where
defined:
data is defined within the