Download A plain white background version

Document related concepts
no text concepts found
Transcript
M874 Weekend School
An Introduction to Java Programming
M874 Java
1
Contents
• Presentation 1,
Objects
• Presentation 2,
Inheritance
• Presentation 3,
Exceptions
• Presentation 4,
Abstraction
• Presentation 5,
Threads
• Presentation 6,
• HCI
• Presentation 7,
Packages
• Presentation 8,
Applets
• Presentation 9,
Network facilities
M874 Java
2
Presentation 1
Aims
•
•
•
•
Describe what an object is
Outline how objects communicate
Introduce the idea of a class
Provide explanations of the vocabulary
terms method, argument, class and object
M874 Java
3
Objects
• Objects occur in everyday life.
• Typical objects in an air-traffic control
system are planes, radars and slots.
• An object is associated with data (state)
• Objects can send messages to each other.
• One of the first activities in a project that
uses Java is identifying objects.
M874 Java
4
Objects
Objects communicate via messages
Plane
I
have
moved my
position
M874 Java
Radar
5
Objects and Messages
The general form of a message
destinationObject.selector(arguments)
Object
message is
sent to
Name of
message
M874 Java
Any
arguments
6
Examples of Messages
Note that
messages can
have no arguments
printer.start()
queued(newProcess)
canvas.drawline(x1,x2,y1,y2)
M874 Java
7
Java Errors 1
• Forgetting that there is a destination object.
• Missing the arguments.
• If the message has no arguments then
omitting the brackets.
M874 Java
8
Classes
• The class is the key idea in an OO language.
• Classes are like biscuit cutters: they can be
used to create objects.
• Classes define the data that makes up an
object.
• They also define the messages sent to an
object and the processing that occurs.
M874 Java
9
Class Skeleton
Note capitalisation
class Example{
definition of state
…
definition of methods
}
State can follow methods
Brackets match
M874 Java
10
An Example of a Class
class Simple{
int x;
add(int k){
x+=k;
}
set(int k){
x = k
}
}
Class with
a single piece of data
(instance variable) and
two chunks of code known
as methods
M874 Java
11
The main Method
• This is a method inserted into the only
public class in a file.
• It carries out execution of a program and
acts like a driver program.
• It must be placed in the class:it is a method.
• It is of the form public static void
main.
M874 Java
12
What Happens
Example e;
…
e.set(8);
…
e.add(12);
Java finds that e is an
Example, looks for
set and then copies
8 into k which is then
copied into x
Java finds that e is an
Example, looks for
add and then copies 12
into k which is then
added to x.
M874 Java
13
Constructors
• Constructors are special methods which are
used to create space for objects.
• They have a special syntax.
• They are used in conjunction with the new
facility.
• They can be associated with any number of
arguments ranging from zero.
M874 Java
14
Example of the Use of a
Constructor
Example e = new Example();
…
Example f = new Example(23);
What happens when
the new facility is
used?
M874 Java
15
How it Works
• If you declare no constructors then the Java
system will initialise all your scalar
instance variables to some default, for
example an int will be 0.It will also
initialise all object instance variables to null
• This is poor programming so you need to
define all your constructors.
• Roughly same syntax as methods.
M874 Java
16
Examples of Constructors
Example(){
x = 0;
}
First constructor
is equivalent to default
Example(int startValue){
x = startValue;
}
M874 Java
Second constructor
initialises instance
variable x to argument
startValue
17
What Happens
Example(12);
Java system looks for a class
Example, then looks for a single
argument constructor, if it finds it
then it carries out the code defined
by the constructor
M874 Java
18
Java Errors 2
• Wrong number and type of arguments in
method call.
• Omitting a constructor.
• Misspelling or lower case/upper case
problems.
M874 Java
19
The Use of this
• The keyword this has two functions in
Java.
• It is used within constructors to enable
maintainable code to be written.
• It is used in methods to refer to the current
instance variables.
M874 Java
20
this in Constructors
class Example{
int u;
Example(int val){
u = val;
}
Use the constructor
defined in this class
which has a single int
argument
Example(){
this(0);
}
}
M874 Java
21
this in Methods
class Example{
int k;
setValue(int k){
this.k = k;
}
…
}
Set the instance variable
in this class to the
value of the argument of
the method
M874 Java
22
public, private etc.
• There are a number of visibility modifiers in
Java.
• You will mainly come across public and
private.
• public means everything is allowed
access.
• private means only entities within a
class are allowed access.
M874 Java
23
Compiling Java Classes
• A file can contain any number of Java
classes. However, only one can be public
• If you have a number of public classes then
place them in separate files
• Good design dictates that instance variables
are private and methods are normally
public.
M874 Java
24
Java Errors 3
• Forgetting that one class in a file must be
public.
• Forgetting to name the source file the same
as the class name.
M874 Java
25
Methods
• Just like subroutines.
• Pass objects as references and scalar types
as values.
• Prefaced with visibility modifiers.
• A number of return types including scalar,
classes and void.
M874 Java
26
Example
public int exCalc(int a, String b){
return someValue;
}
This is the method exCalc
it returns an int value and
has two arguments an int
and a String
M874 Java
27
Presentation 2
Aims
• Describe the rationale behind OO
languages.
• Show how an OO system consist of class
hierarchies.
• Describe the main reuse facility within
Java: inheritance.
• Describe the use of class (static methods).
M874 Java
28
The Notion of Hierarchy
Plane
CargoPlane
B747
FighterPlane
B757
M874 Java
Passenger
Plane
AirbA320
29
Hierarchy 1
• Classes in a computer system can be
arranged in a hierarchy.
• As you go down the hierarchy the classes
become more and more specialised: Plane,
PassengerPlane, B757.
• As you go down the hierarchy more and
more facilities are added.
M874 Java
30
Hierarchy 2
• For example, in a Personnel system you
might have a section of hierarchy:
Employee - SalariedEmployee ComissionPaidSalariedEmployee.
• In this example more and more methods
and instance variables are added as you
proceed down the hierarchy. The way that
this is achieved is via inheritance.
M874 Java
31
Inheritance 1
• Is the most important concept in OO
languages.
• Implemented mainly by the extends
facility.
• Various rules are used to determine what
methods and instance variables are
inherited.
M874 Java
32
Inheritance 2
• If a class A inherits from a class B, then the
methods and instance variables of A become
associated with objects defined by A.
• For example, if PassengerPlane
inherits from Plane then an instance
variable describing the size of the plane
would be inherited from Plane.
M874 Java
33
Inheritance in Java
class A{
instance variables of A a1, a2, a3
methods of A m1, m2, m3
}
class B extends A{
instance variables of B b1, b2
methods of B n1, n2
}
Any object described by B
will have five instance
variables and can respond to the
five messages m1, m2, m3, n1, n2
M874 Java
34
Reuse
Inheritance is the way that reuse is implemented in
any OO language. You will need to be completely
happy with this notion to use such a language. It will
crop up time and time again, for example, to create
a window in Java you will need to inherit from a
built-in class Frame.
M874 Java
35
The two Uses of Inheritance
• There are two uses of inheritance in Java.
• The first use is where functionality is added
to an existing class, for example a
WeeklyPaidEmployee class might
inherit from an Employee class.
• The second use is where functionality is
changed. This is an example of overriding.
M874 Java
36
Overriding
class A{
instance variables
methods m1, m2, m3
}
class B extends A{
instance variables
methods m2,m4,m5
}
When an m2 message is sent to
a B object the m2 method
within c is executed
M874 Java
37
Superclass and Subclass
Superclass
extends
super
this
Subclass
M874 Java
38
Conventions for Naming
• this refers to this class.
• super refers to the superclass.
• both this and super allow you to refer to
the instance variables and methods in a
class and its immediate super class.
M874 Java
39
Using super in Constructors
• You may remember that we can use the
keyword this within constructors.
• In a similar fashion we can use super in
constructors.
• When it is used it calls on the constructor in
the superclass.
M874 Java
40
Example of super
class A{
int instVar;
class B extends A{
int anotherVar;
A(int b){
instVar = b;
}
…
}
B(int c, int d){
super(d);
anotherVar = c;
}
…
}
M874 Java
initialises the
instance variable
inherited from
A with the value
d
41
Static Methods
These are methods whose messages are not sent to
objects but to classes. A static method is prefaced
with the keyword static. You can also have static
variables. These are class globals which are not replicated
in each object defined by a class.
In Java static methods are usually used to implement
general purpose functions such as sin, cos and string
conversion functions.
M874 Java
42
Example of Static Methods
The static method valueOf found in java.lang
public static String valueOf(int v)
Places in val
the string value
of the integer
23
String val = String.valueOf(23);
Note the class name
M874 Java
43
Java Errors 3
• Forgetting the class name when calling a
static method.
• Forgetting to use super within a constructor.
• Initialising instance variables in their
definitions rather than in the constructors.
M874 Java
44
Presentation 3
Aims
• To describe how Java handles errors.
• To show how exception objects can be used
for monitoring errors.
• To describe the use of the throws and
throw keyword.
• To describe the use of the try-catch
facility.
M874 Java
45
Errors
Errors can occur any time within a Java program
•A program runs out of memory.
•An invalid URL is accessed.
•A user types in a floating point number
when an integer is expected.
•A program which expects a file containing data
is connected up to an empty file.
•An array overflows.
M874 Java
46
Exceptions
• Are a way of handling errors which cannot
be anticipated such as mistyped data being
provided by the user.
• Based on the idea of an exception object.
• The keyword throw creates an exception
object which indicates that a problem has
occurred.
M874 Java
47
Creating an Exception
If something has gone wrong then create a new
exception object and throw it. IllegalArgumentException is a build in class in Java.
if(error condition){
throw new IllegalArgumentException();
}
M874 Java
48
Handling Exceptions
• When an exception is created control is
passed to error-handling code.
• This error handling code is introduced by
means of the try-catch facility.
• A number of exceptions can be handled in
the same body of code.
M874 Java
49
Using try-catch
try{
// Code which potentially causes two exceptions
// IllegalArgumentException and NumberFormat
// Exception
}
catch(IllegalArgumentException i)
{Code for processing the IllegalArgumentException}
catch(NumberFormatException n)
{Code for processing the NumberFormatException}
M874 Java
50
try-catch
• When an Exception object has been
created in the code enclosed by a trycatch control is transferred to the code
corresponding to the exception.
• The identifier introduced, for example i in
the previous slide is assigned to the
exception object and the code within the
curly brackets executed.
M874 Java
51
An Example
try{
if(!name.equals(“URL”))
throw new IllegalArgumentException();
}
catch(IllegalArgumentException i)
{System.out.println(“Problems with URL”)}
There is no
reference to i here.
M874 Java
52
Referring to Exception Objects
try{
if(!name.equals(“URL”))
throw new IllegalArgumentException();
}
catch(IllegalArgumentException i)
{System.out.println(“Problems with URL”+i)}
Will print out details of
the exception i
M874 Java
53
The throws Keyword
• This keyword is placed within the header of
methods.
• It indicates that an Exception object has
been thrown in the code but no trycatch processing has occurred.
• Any method that calls this method either
has to use try-catch or head itself with
throws.
M874 Java
54
Using Throws
public String process(int j)throws IllegalArgumentException
{
// Processing involving j
if (j<0)
throw new IllegalArgumentException();
// Processing which eventually returns a string
}
M874 Java
55
The Chain of Exception Handling
If you have a number of methods which call each other
somewhere a method will have to have a try-catch in it.
Also, the compiler will carry out a check that if an
Exception object is thrown in the code of a method
either the method handles the exception by try-catch or
advertises the fact that it will be thrown upwards.
M874 Java
56
Creating your own exceptions
You can easily create your own exceptions by inheriting
from an existing exception class.
class MyException extends IllegalArgumentException{
}
Effective renaming
M874 Java
57
Presentation 4
Aims
• To introduce the concept of design facilities
in Java.
• To show how abstract classes embody ideas
of abstraction .
• To show how interfaces implement a form
of multiple inheritance.
M874 Java
58
Abstraction
Employee
Contains
code for
common bits of
an employee, for
example the name
CommisionEmployee
M874 Java
Contains
bits necessary
for the class,
for example,
commission
rate
59
Abstract classes
• Are classes where some of the methods are
left blank.
• If a programmer wishes to create an object
from an abstract class then an error will
occur.
• To produce objects classes need to inherit
from the abstract class and override blank
methods.
M874 Java
60
Example of Abstract class
abstract class Employee{
...
public abstract int calculatePay();
…
}
class SalariedEmployee extends Employee{
…
public int calculatePay(){
//Programmer has inserted the code here
}
}
M874 Java
61
Abstract classes
• If you inherit from an abstract class then
you have to provide the code for the
absytact methods in the class, otherwise
your resulting class will still be abstract.
• Abstract classes provide a way of saying: if
you are going to create an object of a certain
class you are going to have to implement
certain method(s).
M874 Java
62
Interfaces
• Interfaces are similar to abstract classes.
• The main difference is that all the methods
in an interface are blank.
• Used to implement multiple inheritance.
• Can deliver constants but not variables.
M874 Java
63
Multiple inheritance
Single inheritance
Multiple inheritance
M874 Java
64
Problems with Multiple
Inheritance
• Inefficient.
• Unreliable.
• Complex naming conventions.
M874 Java
65
The Solution- Interfaces
• If a class implements an interface then it must provide
code for all the methods in the interface.
• It provides a form of certification of all the classes that
carry out the implements operation.
• Important uses include implementing threads and also
enumerators.
• Has achieved greater importance due to its use in the Java
event model.
M874 Java
66
Example
B
C
class A extends B implements C{
A
}
Code here for all the
methods in C and some
code which could override
methods in B
M874 Java
67
The Enumeration Interface
• One of the most difficult concepts to
understand in Java.
• Enables the programmer to iterate over the
elements of a collection without knowing
how the collection is stored.
• You need to form an iterator with a
constructor which supplies code for the
Enumeration methods.
M874 Java
68
Enumeration
class Iterator implements Enumeration{
Iterator(arguments){
…
}
…
// Code for methods of Enumeration
}
M874 Java
Needed to
pass collection
data across
69
Enumeration methods
• Contains two methods.
• hasMoreElements, returns true if there
are more elements to process.
• nextElement returns a value from an
Enumeration and moves to the next
object, note that it returns an object defined
by Object.
M874 Java
70
Example of the use of an
Enumeration
iter = new Iterator(a);
..
while(iter.hasMoreElements()){
...
Object o =iter.nextElement();
...
}
M874 Java
Code for the
processing of each
element, make
sure
that the code
processes
an Object
71
Presentation 5
Aims
• To describe the concept of a Thread.
• To show how Java implements threads via
the Runnable interface.
• To describe some thread methods.
M874 Java
72
Threads
• A thread is a chunk of code which can be
executed concurrently with other threads.
• Many Internet/Intrenet applications are
inherently threaded.
• Threads are normally implemented by using
implements on the Runnable interface.
M874 Java
73
Thread Code
class MyThread implements Runnable{
//Any instance variables
…
public void run(){
//Code for thread
This
}
is the code
for the thread
new thread objects
will be created by
new
}
M874 Java
74
Manipulating threads
• Threads are created by the new keyword.
• This does not start them the method start does this.
• There are a wide variety of methods to manipulate threads,
for example to kill threads and suspend them.
• Threads continue executing until they finish their run code,
sometimes for ever.
• The thread class has a constructor of type Runnable, this
uses an object which implements the Runnable interface.
M874 Java
75
More thread code
class LpThreader implements Runnable{
int value;
LpThreader(int limit){
// code for constructor sets value
}
…
public void run(){
// Code for thread possibly accessing value
// which is local to the thread
}
...
}
Remember to start a thread
use start after it has been created
M874 Java
76
Thread Methods
• start, starts a created thread executing.
• stop, stops a thread from running.
• suspend, temporarily stops a thread from
executing.
• resume, starts a suspended thread up
again.
• setPriority, sets the priority of a
thread.
M874 Java
77
The sleep Method
• This puts a thread to sleep for a number of
milliseconds.
• It is static.
• Used when there is no work yet for a thread
to do, for example it may be waiting for
some data to process.
• Throws an InterruptedException.
M874 Java
78
An Example Sleep
Sleep for 100 ms
try{
Thread.sleep(100);
}
catch InterruptedException e){
// Interrupt code here
};
A thread may try to interrupt a sleeping
thread, this is an error so sleep throws
an InterruptedException which must
be caught
M874 Java
79
Presentation 6
Aims
• To describe how windows-based
programming is carried out in Java.
• To show how widgets are laid out.
• To describe the main Java widgets.
• To describe how user events are caught and
processed.
M874 Java
80
The Java AWT
• Implemented as a package.
• Portable-draws on the underlying widget set
of the base OS, for example Motif or
System7 widgets.
• A number of aspects to programming:
creation, layout and responding to events.
M874 Java
81
Components and Containers
• In Java you have widgets and containers.
• Widgets are individual elements such as
Button and TextArea.
• Containers hold components, for example
Frame.
M874 Java
82
Containers
• These are the elements used to contain
widgets.
• Typical Java containers are Frame,
Dialog, Panel and Applet.
• Panel is a notional container used for layout
purposes: a Panel can be nested inside a
Panel which in turn can be nested in a Panel
etc.
M874 Java
83
Programming the AWT
• First you need to extend an AWT class like
Frame.
• Next you need to create the components in a
constructor.
• Next you need to set a layout in the
constructor.
• Then you need to add the components to the
container.
M874 Java
84
The final step
The final step is to program what should occur when
some action such as pressing a button occurs. This is
rather picky programming but not too difficult to
grasp.
M874 Java
85
Creating the Components
class MyFrame extends Frame{
Button b;
TextField t;
Note the use of
the super constructor to
set up the frame
MyFrame(){
super();
...
b = new Button(“Press”);
t = New TextField(“000”);
}
…
}
M874 Java
86
Java Errors 4
• Forgetting to create the widget in the
constructor.
• For a container forgetting to use super to
create an instance of the container.
M874 Java
87
Layout
The next step is to lay the components out. For this you
will need to set some layout pattern on your container.
You use the method setLayout for this, but before you
use this method you will need to create a layout object.
There are a number of layout classes. The course
concentrates on the simplest.
M874 Java
88
Layouts
• FlowLayout, just flows the components.
• GridLayout uses a two dimensional grid.
• BorderLayout uses the points of the
compass.
• CardLayout is used for tabbed dialogues.
• GridBagLayout is a massively complex
layout.
M874 Java
89
FlowLayout
As components are added they are flowed into
the container at the next available position. This
is the default layout for applets.
There is no default layout for any other container,
they need to be specified.
M874 Java
90
Example of FlowLayout
MyFrame(){
super();
b = new Button(“Hello”);
c = new Button (“Press”);
setLayout(new FlowLayout());
add(b);
add(c);
}
Anonymous
layout object
Means this.add
M874 Java
91
GridLayout
• Based on a row and column grid.
• Constructor requires to int values for rows
and column numbers.
• add works left to right and top to bottom.
M874 Java
92
GridLayout Example
MyFrame(){
super();
b = new Button(“Hello”);
t1 = new TextArea(“000”);
c = new Button (“Press”);
t2 = new TextArea(“000”);
setLayout(new GridLayout(2,2));
add(b);
add(c);
add(t1);
add(t2);
}
M874 Java
93
BorderLayout
• Based on four points of the compass and
center.
• Restricted to five or less elements.
M874 Java
94
BorderLayout example
MyFrame(){
super();
b = new Button(“Hello”);
t1 = new TextArea(“000”);
c = new Button (“Press”);
t2 = new TextArea(“000”);
setLayout(new BorderLayout(2,2));
add(“North”, b);
add(“South”, c);
add(“Center”,t1);
add(“West”, t2);
}
M874 Java
You can also use
constants such as
Borderlayout.
NORTH
Adds four
components
note the spelling of
Center
95
Processing user actions
• There are various user actions which the
AWT is designed to catch.
• Examples are: button pressed, slider moved,
menu clicked, text entered into an text
component.
• A new event model was introduced into
Java 1.1 to process events.
M874 Java
96
The Java event model
• Requires objects such as applets which need
to respond to events to be registered as
listeners to the event.
• These objects must implement listener
interfaces.
• These objects must be registered to listen to
events, usually in the constructor.
M874 Java
97
Event Example
import java.awt.*;
import java.awt.event.*;
public class ButtonExample extends Frame implements ActionListener{
Button b1;
public ButtonExample(){
setLayout(new FlowLayout());
b1 = new Button(“Press me”);
add(b1);
b1.addActionListener(this);
pack();
}
M874 Java
98
Event Example
public void actionPerformed(ActionEvent e){
System.out.println(“My button has been pressed”);
System.exit(0);
}
public static void main(String[] args){
ButtonExample bf = new ButtonExample();
bf.setVisible(true);
}
}
M874 Java
99
Events
• Although this is a simple example it shows
the general form of processing.
• An object implements a listener interface.
• An object which implements a listener
interface is registered as being a listener of
the object causing the event.
• Code is provided in the methods that have
to be implemented to respond to events.
M874 Java
100
Events
• There a wide variety of events that can
occur, for example events associated with
windows or the mouse.
• However, the general model is the same.
• One problem is that some interfaces contain
a number of methods and you may only
need to provide code for a few.
M874 Java
101
Events
• One solution is to include blank bodies
within the code for these methods.
• Another solution is to develop an inner
class.
• This is a class which has access to the class
in which it is embedded and which extends
an adapter class.
M874 Java
102
Adapter classes
• An adapter class is a class which
corresponds to a listener interface but has
blank code supplied for all its methods.
• The inner class just extends the adapter
class and supplies code for any of the
methods which are required to respond to
events.
M874 Java
103
Example
Class Example{
Example(){
..
WindowCloser w = new WindowCloser();
addWindowListener(w);
..
}
class WindowCloser extends WindowAdapter{
public void windowClosing(WindowEvent w){
System.exit(0);
}
}
M874 Java
104
The Canvas class
• Is an invisible container.
• Used to arrange items on a visible container.
• Panels can be nested within each other
providing a high degree of flexibility.
M874 Java
105
Example of a Canvas
MyFrame(){
// Code here for initialisation and for setting the
// layout manager for the frame.
p1 = new Panel(); p2 = new Panel();
b1 = new Button(“Press”); b2 = new Button(“Here”);
t1 = new TextArea(20); t2 = new TextArea(30);
p1.setLayout(new FlowLayout());
p2.setLayout(new GridLayout(1,2));
p1.add(b1); p1.add(t1);
p2.add(b2); p2.add(t2);
add(p1); add(p2);
M874 Java
106
Drawing
• You can draw on any component.
• Every component provides a method
paint which can be overridden to provide
drawing.
• Normally we only draw on objects
described by the Canvas class.
M874 Java
107
Example of drawing
MyFrame(){
…
c = new Canvas();
…
}
paint(Graphics g){
// Code her which carries out drawing
}
M874 Java
108
paint
• paint has a Graphics object as its
argument.
• paint is called automatically when
containers are moved, resized etc.
• In order to program a paint operation you
need to call repaint.
• All drawing is done via sending messages to
the Graphics argument.
M874 Java
109
Presentation 7
Aims
•
•
•
•
To introduce the idea of a package.
To introduce the main Java packages.
To detail the role of the Object class.
To show how the Object class can be
used for general purpose data structures.
M874 Java
110
Packages
• These provide the libraries which Java uses,
Java is a small language and gets its power
from the facilities found in the libraries.
• Packages, apart from java.lang have to
be imported.
• You can import individual classes.
M874 Java
111
HTML Documentation
• Documentation for the class libraries is
stored using HTML and can be accessed
using your favourite browser.
• The documentation gives the naem of the
class all its instance variables and all its
methods.
• You should be totally familiar with ways of
accessing this documentation.
M874 Java
112
Java Errors 5
• Forgetting to import a package.
• When consulting a class description for a
method forgetting that it may inherit from a
class which contains that method, for
example TextArea.
• Forgetting that a method may be static
• Treating * as a full wildcard.
M874 Java
113
import
• Is used to tell the compiler which classes
could be used.
• import can import the whole of a package
or a single class
import java.awt.*;
import java.awt.Button;
M874 Java
114
The Main Packages
• java.lang contains base facilities.
• java.io contains stream-based facilities.
• java.net contains network programming
facilities.
• java.util is a general purpose package
containing data structure and useful classes
such as Date.
• java.awt contains HCI facilities.
M874 Java
115
The Object Class
• One feature of some of the classes in the
Java library is the fact that the Object
class is used.
• Object is a class which lies at the top of
the object hierarchy.
• Every class either explicitly or implicity
inherits from Object.
M874 Java
116
Assignments and casting
• Assignments between objects in a hierarchy
are allowed provided they are on an
inheritance chain.
• Two categories of assignment up-casting or
down-casting.
• Up-casting can use normal assignment.
• Down-casting involves a cast construct.
M874 Java
117
Examples of Assignments
A a
…
B b
…
a =
…
b =
...
= new A();
We assume that B inherits
(extends) A
= new B();
b;
a;
Legal
Illegal you need to
write
b = (B) a;
M874 Java
118
Rules
• In an assignment a = b, provided a is a
superclass of a then everything will be ok.
• However b = a requires the bracketed
cast.
• In the first instance the values of instance
variables associated with the subclass object
are hidden.
• In the second instance they are made
visible.
M874 Java
119
This holds for objects described
by Object
Object o;
…
class A{
…
}
a = new A();
…
o = a;
…
a = (A) o;
Both of these are legal
M874 Java
120
Why use Object?
• In the course there is one important use of
Object.
• It is used as a container for any type of
object.
• Gives a number of difficulties when
retrieving or adding an item from a
collection.
M874 Java
121
Example
This should add the
int 19 at the 23rd
location in the Vector,
does it?
Vector v = new Vector(50);
…
v.insertElementAt(19,23);
…
int val = elementAt(19)
This should retrieve the
element at position
19 and place it in val, does it?
M874 Java
122
The Answer is No
If you look in the HTML documentation for
insertElementAt()the first item should be
an Object, it is a scalar.
If you look in the documentation for elementAt,
then the returned object is of class Object, and
hence we are trying to assign an object to a scalar.
M874 Java
123
The Correct Version
Vector v = new Vector(50);
…
v.insertElementAt(new Integer(19),23);
…
int val = ((Integer)v.elementAt(19)).intValue();
M874 Java
124
The Writing Part of the Example
v.insertElementAt(new Integer(19),23)
An object has to be created
we use a special class called
Integer to do this, such a class
is known as an object wrapper
M874 Java
125
The Reading Part of the Example
This returns with the
int value of the Integer
object
We need an int
int val = ((Integer)v.elementAt(19)).intValue();
This casts the object
defined by Object into
an Integer object
M874 Java
126
Object Wrappers
• Used to move between objects and scalars
in impure object-oriented languages.
• Java contains a number of object wrappers
for its scalars.
• Each object wrapper contains methods for
conversions, warning: they are often static.
M874 Java
127
Presentation 8
Aims
• To describe how applets are constructed.
• To describe the main applet methods.
• To show how applets interact with a
browser.
M874 Java
128
Applets
• Snippets of compiled code embedded in a
Web page.
• Applets loaded when browser page is
invoked.
• There are a number of applet life-cycle
methods.
• Developing applets is different to normal
development.
M874 Java
129
Applets and Browsers
Class file loaded
into client
Server
security
restrictions
M874 Java
Browser
130
Security Restrictions
The applet cannot
• Execute programs on the client.
• Read a file on the client.
• Write to the client.
• Find out system information about the
client.
M874 Java
131
Developing Applets
• Extend the class Applet.
• Provide the code.
• Compile the code.
• Embed the class file produced by
compilation in a Web page via special
HTML tags.
M874 Java
132
Applets and Containers
• An applet is just like a container.
• It inherits all the methods associated with
containers.
• It can have a layout manager associated
with it although the default is
flowLayout.
M874 Java
133
Applet Code
• The main difference between an applet and
other containers such as Frame is that there
is no applet constructor.
• Initialisation is done in a method init.
• init is an example of a life-cycle method.
• Applets are created by inheriting from
Applet which contains these methods.
M874 Java
134
Applet Code
class MyApplet extends Applet{
// instance variables
public void init(){
//initialisation of variables
//construction of Layout objects
//initialising files etc.
}
// other overidden methods
}
M874 Java
135
Other Life-cycle Methods
• init, called by the Java system when the
applet is loaded or reloaded.
• start, called when the applet has been
loaded and can start.
• stop, called when the user leaves the
browser page or exits from the browser.
M874 Java
136
Java Errors 6
• Attempting to execute an applet using
java.
• Writing a constructor for an Applet.
• Missing out the full signature of a life-cycle
method, for example missing public.
• Trying to embed an applet inside another
container such as a frame.
M874 Java
137
Applets as Containers
• Applets are containers.
• Hence other containers such as Panel and
Canvas can be embedded in them.
• Also, components such as buttons and
sliders can be placed in them.
• They inherit all the component methods
such as paint, mouseDown.
M874 Java
138
Tags for Applets
<APPLET
CODE = MyApplet.class
WIDTH = 200
HEIGHT = 300 >
<PARAM NAME = Color VALUE = “Red”>
<PARAM NAME = Font VALUE = “Times”>
</APPLET>
This applet will be found in the file
MyApplet.class, it will be 200 pixels by
300 and have two parameters
M874 Java
139
Applet Methods
• The Applet class is a small one, but it
does contain a number of important
methods.
• Contains life-cycle methods.
• getParameter which gets parameter
values.
• showStatus which displays strings on
your browser’s status bar.
M874 Java
140
Presentation 9
Aims
• To outline the main net facilities of Java.
• To describe the URL class.
• To describe the URLConnection class.
• To show how connections can be made to
remote computers.
M874 Java
141
The URL class
• Describes URLs, Universal Resource
Locators.
• Contains a number of constructors to form
URLs.
• Also contains a number of methods which
access various components of a URL.
M874 Java
142
A URL
http://www.open.ac.uk/Studentweb/M874/
Protocol
Location
M874 Java
File
143
The class URLConnection
• Establishes a network connection to a given
URL.
• Used to connect across to files on a remote
computer.
• Also enables some information to be
extracted from a URL.
M874 Java
144
Some accessor methods
• getLastModified()
• getContentLength()
• getDate()
All return information about the file referenced by the URL
M874 Java
145
Code example
String urGiven = “http://www.open.ac.uk/Base/Data.txt
uConnect = new URLConnection(urGiven);
InputStream is = uConnect.getInputStream();
DataInputStream di = new DataInputStream(is);
We can now read from the file using
methods such as readInt.
M874 Java
146
Applet transfer
• The previous example described how to
connect up to a file which has a URL.
• If you want to transfer browser control to a
URL which references a web page you need
to use.
M874 Java
147
Example
AppletContext a = getAppletContext();
URL ur = new URL(
http://www.open.ac.uk/Appl5/home.html”);
a.showDocument(ur);
Note that an appletContext is a data structure used
to interface to a browser. The effect of the above is to
show the document referenced on the second line
in the browser.
M874 Java
148
Sockets
• Sockets are used to plug into a remote
computer.
• A number of constructors are associated
with a socket.
• Objects described by Socket can be used
to transfer data into and out of a remote
computer.
M874 Java
149
Example
Port 37 is the Time
port on a computer
String hst = “www.open..ac.uk”;
Socket s = new Socket(hst, 37);
InputStream is = s.getInputStream();
DataInput Stream ds = new DataInputStream(is);
We can now read from the 37 port
using the methods found in class
DataInputStream
M874 Java
150
ServerSockets
• These are used to establish connections to
clients.
• Are associated with a port.
• Use the accept method which waits for a
connection.
• Uses input and output streams.
M874 Java
151
An example of a simple server
written in Java
import java.awt.*;
import java.net.*;
import java.io.*;
public class SimplCon
{
public static void startServer()
{
ServerSocket ss=null;
Socket s = null;
PrintStream dos = null;
OutputStream os = null;
String st;
int count = 0, loopCount =1;
try{
// Server uses port 1024, clients need to use this port
ss= new ServerSocket(1024);
}catch(Exception e){System.out.println("Error:Socket not set up");}
M874 Java
152
Server code
while (true){
try{
System.out.println("Waiting for connection "+loopCount);
//Server now blocks waiting for a client
s = ss.accept();
}catch(Exception e){System.out.println("Error:Problem with connection");}
loopCount++;
FileInputStream fi=null;
try{
os = s.getOutputStream();
dos = new PrintStream(os,true);
}catch(Exception e){System.out.println("Error:Problem setting up output stream");}
// Server uses the text in file Emails.txt to send to clients
// This file must be in the same directory as the server
try{
fi =new FileInputStream("Emails.txt");
}catch(FileNotFoundException fnf){System.out.println("Error:File not found");}
DataInputStream di = new DataInputStream(fi);
try{
st = di.readLine();
while (st!= null){
count++;
dos.println(st);
st = di.readLine();
}
M874 Java
153
Server code
fi.close();
dos.close();
s.close();
di.close();
}catch(Exception e){System.out.println("Error:Problem with reading");}
System.out.println(count+ " lines of text read");
try{
Thread.sleep(3000);
}catch(Exception e){};
}
}
static public void main(String args[])
{startServer();
}
}
M874 Java
154