Download Introduction to Software Engineering

yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project

Document related concepts

Object-relational impedance mismatch wikipedia, lookup

Relational model wikipedia, lookup

Go (programming language) wikipedia, lookup

Object-oriented programming wikipedia, lookup

C Sharp (programming language) wikipedia, lookup

Falcon (programming language) wikipedia, lookup

C++ wikipedia, lookup

Java ConcurrentMap wikipedia, lookup

C Sharp syntax wikipedia, lookup

Java performance wikipedia, lookup

Class (computer programming) wikipedia, lookup

Java (programming language) wikipedia, lookup

Design Patterns wikipedia, lookup

Name mangling wikipedia, lookup

C syntax wikipedia, lookup

Scala (programming language) wikipedia, lookup

Version control wikipedia, lookup

Java syntax wikipedia, lookup

Covariance and contravariance (computer science) wikipedia, lookup

Smalltalk wikipedia, lookup

CE203 - Application Programming
Autumn 2015
CE203 Revision
Java Characteristics
Object Oriented
( Source: LIANG, Y.D., “Introduction to Java Programming”, 6th Edition, Prentice-Hall, 2007)
Autumn 2015
CE203 Revision
Object Orientation - Attributes
Both class and object can have attributes
Attributes in Java are simply called variables
Class variables are shared by all instances of the class
Instance variables belong to a particular instance (or
• The state of an object is given by the values of its instance
Autumn 2015
CE203 Revision
Object Orientation – Information Hiding
• External access to an object’s attributes and methods is
controlled by means of the scope modifiers private,
public and protected
• Direct access to attributes is usually prohibited
• Access is usually gained through secure public methods
Autumn 2015
CE203 Revision
Object Orientation:
Composition & Specialisation
Autumn 2015
CE203 Revision
Parameterisation and References
• In Java, objects are “reference types” (unlike primitive
data types!)  the value passed when the actual
parameter is an object is a reference.
• Parameters of primitive type are always passed using call
by value  the value associated with the actual parameter
cannot be changed
• Parameters that are objects are always passed using call
by reference  the value(s) associated with the actual
parameter can be changed
Autumn 2015
CE203 Revision
Method Overloading
We can supply several definitions for a method sum within
the same class definition, as long as each definition has a
different set of input types.
int sum (int i, int j)
{return i + j;}
// version 1
double sum (double e, double f) // version 2
{return e + f;}
int sum (int i, int j, int k)
{return i + j + k;}
Autumn 2015
CE203 Revision
// version 3
Method Overloading 2
sum(4, 5)
sum(4.5, 5.5)
sum(4, 5, 6)
will call version 1 on the previous slide
will call version 2 on the previous slide
will call version 3 on the previous slide
This process is known as static binding, because the decision
about which version of the method to apply is made at the
compilation stage.
Autumn 2015
CE203 Revision
Accessibility Rules
1. With no modifier, access is permitted from anywhere
in the enclosing package.
2. The public modifier permits access from beyond the
enclosing package.
3. The private modifier prevents access from outside
the enclosing class.
4. The most restrictive modification applies
Autumn 2015
CE203 Revision
Specialisation hierarchies and Interfaces are closely related
 They both provide support for polymorphism
(the ability to define methods that can operate on many
different types) which is implemented by means of
dynamic binding (which means that the decision about
which version of the method should be applied is made
while the program is executing)
Autumn 2015
CE203 Revision
Specialisation – Dynamic Binding
When a method has been redefined (possibly more than
once) in a hierarchy of classes, and that method is called on
an object, then the closest definition (going up the hierarchy
from the object’s class) is applied, for example:
Autumn 2015
CE203 Revision
Specialisation – Dynamic Binding 2
Example (continued):
Autumn 2015
CE203 Revision
Java Applets 2
When an HTML browser visits a page containing the applet
the applet container will create an applet object and display it
on the page. An applet class does not have a main method
since the container effectively plays this role.
When the applet is displayed its paint method will be called
– a default one inherited from the JApplet class will be used
if the class has no such method.
The paint method takes an argument of type Graphics – we
can apply methods to this argument to draw items on the
(Reminder: applets = one way to illustrate general principles)
Autumn 2015
CE203 Revision
Event-Driven Programming 1
In traditional procedural programming a main method calls
other methods, which may themselves call further methods,
so the sequence in which methods are called can be
determined by examining the program or input data.
In event-driven programming, however, after performing
initialisation the program simply waits for events to occur
and responds to them – the programmer must write methods
to be called when particular events occur.
Autumn 2015
CE203 Revision
Event-Driven Programming 3
When the programmer wishes to respond to events associated
with a particular component he or she must add an action
listener to that component. This must be an object belonging
to a class that implements the interface ActionListener,
and is added to the component using the method
addActionListener, e.g.
but.addActionListener(new ButtonHandler());
There is a similar interface called
MouseListener for mouse events not associated with
components, and there are many more interfaces like this.)
Autumn 2015
CE203 Revision
Handling Multiple Buttons 1
Many applets will require more than one button. If the
buttons perform unrelated tasks a separate action listener
class should be written for each. However, in many cases,
several buttons will perform similar tasks and it will be
inefficient to write separate action listener classes.
Two approaches are possible: we can create separate objects
for each button, supplying an argument to the constructor to
indicate which is which, or create a single object, in which
case it is necessary to determine in the actionPerformed
method which button has been pressed.
Autumn 2015
CE203 Revision
Exceptions 2
A method that detects an error may throw an exception,
which may then be caught by the method that called it or by
some higher level call; if the exception is not caught
execution will be terminated with an error message (unless
the exception occurs when an event-handler is being used in
an applet, in which case the handling of that event will be
In Java all exceptions are class objects and must be a member
of the class Exception, or of some subclass of this class; a
number of subclasses are provided in the standard library, for
example NullPointerException, ArithmeticException
and ArrayIndexOutOfBoundsException.
Autumn 2015
CE203 Revision
Exceptions Summary
Java exceptions are either checked or unchecked.
Checked exceptions have to be handled by the programmer:
• the programmer either has to catch them or declare them
• if this is not done, the compilation will fail
• all IOExceptions are checked exceptions
Unchecked exceptions are different:
• the programmer can choose to catch them or declare them
• if this is not done, the compilation will still succeed
• NumberFormatException is an unchecked exception
Autumn 2015
CE203 Revision
The Java Collections Framework 1
The Java Collections framework provides a number of
classes that can be used to store various kinds of collections
of objects. These kinds are distinguished by properties such
as whether duplicate elements are allowed and whether the
elements have a defined order.
Methods that are common to all collection classes are
declared in an interface called Collection from the package
Autumn 2015
CE203 Revision
The Collections Framework (continued)
Autumn 2015
CE203 Revision
Generics / Parameterised Types
As a consequence of the introduction of generics in Java 5.0
collection classes and interfaces may now be parameterised
by types, e.g. Collection<Integer>.
If a type parameter is provided the argument and result types
of the methods will be more specific than Object, so, for
example, for an object of type Vector<Date> the add
method would expect an argument of type Date and the
elementAt method would return a Date object.
Autumn 2015
CE203 Revision
Iterators 1
Iterators can be used to access the contents of a collection
An iterator may be thought of as a sequence of elements,
together with a place-marker that lies between adjacent
elements in this sequence. The sequence comprises all of the
elements in the collection; for a hash set the order in which
the elements occur in the sequence is unspecified, for a list or
vector the elements will appear in the same order as in the
Autumn 2015
CE203 Revision
Iterators 6
If a collection is parameterised by a type its iterator will also
be parameterised by that type and the next method will
return an object of that type. The following method will
calculate and return the total length of the items in a
collection of strings.
public static int totalLength(
Collection<String> c)
{ Iterator<String> it = c.iterator();
int tot = 0;
while (it.hasNext())
tot +=;
return tot;
Autumn 2015
CE203 Revision
List Iterators 5
We can make use of the set method of the ListIterator
class to write a method that replaces all the strings in a list by
upper-case versions.
public static void upperCase(List<String> l)
{ ListIterator<String> it = l.listIterator();
while (it.hasNext())
String s =;
Autumn 2015
CE203 Revision
The Map Interface 1
The Java Collections Framework provides a further kind of
collection. A map is a collection of pairs of entries each
comprising a key and a value. Elements of a map must have
unique keys, but there may be more than one element with
the same value.
The Map interface does not extend the Collection interface
but provides similar methods.
Autumn 2015
CE203 Revision
Using JDBC 1
JDBC (Java Database Connectivity) allows Java programs to
access and manipulate relational databases using statements
written in the SQL language.
The JDBC application programming interface makes no
assumption about the database other than that it can be
accessed using SQL. Any database supporting SQL may, in
theory, be used (we will use MySQL).
Autumn 2015
CE203 Revision
Using JDBC 9
Having established a connection to the database we need to
create a Statement object to execute SQL statements. This is
done using the createStatement method declared in the
Connection interface. An exception of type SQLException
may again be thrown if there are problems accessing the
Autumn 2015
CE203 Revision
Executing Queries 1
Once a Statement object has been created it can be used as
many times as required to perform SQL queries and updates.
Queries are performed using the executeQuery method,
which takes a string argument and returns a result of type
ResultSet rs = statement.executeQuery(
"SELECT name FROM employees");
An exception of type SQLException may be thrown if the
string is not a valid SQL query.
Autumn 2015
CE203 Revision
Executing Updates
To update a table in a database using SQL INSERT, UPDATE or
DELETE statements we must apply the executeUpdate
method to a Statement object. This method returns a value
of type int, which indicates the number of rows in the table
after the update:
int i = statement.executeUpdate(
"DELETE FROM employees WHERE salary<1000");
"Employees table now has " + i + " rows");
Autumn 2015
CE203 Revision
Using the execute Method 1
If it is necessary to perform actions such as creating a new
table or removing a table the execute method from the
Statement interface should be used. This method can be
used with any SQL statement as an argument so it could
potentially generate a result set. Since in most cases it will
not do so, the method does not return a result set, but instead
returns a boolean value indicating whether a result set has
been generated. If a set has been generated it can be retrieved
using the getResultSet method.
Autumn 2015
CE203 Revision
Closing Connections
After access to a database has been completed it is desirable
to close connections to release resources. The close method
should be applied to any Statement objects that were created
and then to the Connection object (unless you use try-withresources):
{ statement.close();
catch (SQLException e)
{ System.out.println(
"problems closing database");
Autumn 2015
CE203 Revision
Prepared Statements 1
These are really Parameterised Statements (or Stored
Procedures). The idea is that you can write an SQL
statement with question marks as placeholders. e.g.:
String updateString = "update COFFEES " +
"set SALES = ? "
"where COF_NAME like ?";
has two placeholders.
Autumn 2015
CE203 Revision
JDBC Issues 2
More importantly…
• Consider security issues such as SQL Injection
• Explore this issue (e.g. start with Wikipedia) and then try
to break your own JDBC code
• Start with an applet that allows user input which is then
passed to a database via JDBC (e.g. Liang, chapter 37)
• There will be much more on security issues in the guest
Autumn 2015
CE203 Revision
Alternatives to JDBC
• Object Databases
(e.g. see
• Object-relational mapping
• JSON or XML output
• Object serialization
• NoSQL (see
... Collections framework
Exercise: Explore pros and cons of each of these approaches.
Autumn 2015
CE203 Revision
Using Frames 1
We have seen various GUI examples written as applets using
classes that extend the JApplet class. We shall now see how
similar examples can be produced in applications using
classes that extend the JFrame class. We start with a framebased version of the simple greeting program from part 1.
(The usual import statements are needed, but have been
omitted due to lack of space on the slide.)
Autumn 2015
CE203 Revision
Text Areas 1
The JTextArea class permits the display and manipulation of
multiple lines of text.
This class has a constructor with two arguments indicating
the number of visible rows and columns – to create a text area
whose visible area comprises 12 rows of 20 characters we
could use
JTextArea myTextArea = new JTextArea(12,20);
When this two-argument constructor is used the area will
initially contain no text.
Autumn 2015
CE203 Revision
Layout Managers 1
Earlier in this module we encountered two layout manager
classes, BorderLayout and FlowLayout, and saw that we
may specify a layout manager for a container by applying
setLayout. If this method is not called a border layout
manager is used for the container of an applet or frame, but a
flow layout manager is used for a panel.
Autumn 2015
CE203 Revision
Checkboxes 1
A checkbox is a state button that has a boolean value, usually
denoting whether some feature is to be turned on or off.
Objects of type JCheckBox may be added to a frame, applet
or panel in the same way as any other component, but the
handler for the box is different. Instead of adding an action
listener to the box we need to add an item listener which
implements the class ItemListener by providing a void
method called itemStateChanged with an argument of type
ItemEvent. This method will be called whenever the user
clicks on the box to turn it on or off.
Autumn 2015
CE203 Revision
Radio Buttons 1
Radio buttons are similar to checkboxes, but may be grouped
together and at any time exactly one button from a group will
be selected; clicking on another one will deselect the previous
Radio buttons are placed on a frame, applet or panel as
individual components; the grouping is performed as a
separate activity by adding the buttons to an object of type
ButtonGroup; this object is not a component so it is not
added to the container.
Autumn 2015
CE203 Revision
Radio Buttons 2
Event handlers for JRadioButton objects should implement
The example on the following slides shows the use of radio
buttons to control the colour of a square. Note the use of the
boolean argument in the calls to the JRadioButton
constructor to indicate which button is initially selected.
The ItemEvent class has a getSource method similar to that
of ActionEvent; this has been used in the button handler to
determine which radio button the user has selected.
Autumn 2015
CE203 Revision
Menus 1
In order to use menus in a frame or applet we need to add a
menu bar. This contains one or more menus, which are
made up of menu items (or submenus).
Hence three classes need to be used: JMenuBar, JMenu and
This example on the following slides generates a frame in
which the colour of a displayed square is selected from a
Autumn 2015
CE203 Revision
Dialogue Boxes 1
A dialogue box is a window that is temporarily placed on the
screen to display a message for the user or allow him or her
to supply input.
To create and display a message dialogue box the static
method showMessageDialog from the JOptionPane class is
"The answer is " + answer,
Autumn 2015
CE203 Revision
Java Security Manager 1
• Java has been designed to work in a distributed
• Code can be downloaded dynamically from a variety of
(untrusted) sources
• Running such code alongside applications that contain
confidential information poses a potential risk.
• Security is a real concern and built into Java via access
Autumn 2015
CE203 Revision
Java Security Manager 3
Two options to use a security manager:
• Set one via the setSecurityManager method in the
java.lang.System class, i.e..:
System.setSecurityManager(new SecurityManager());
• Call Java using appropriate command line arguments, e.g.:
javac ...
Autumn 2015
CE203 Revision
Java Security Manager 6
Autumn 2015
CE203 Revision