Exam Notes - Application1 1
Exam Notes - Application1 1
md 5/22/2023
state: a set of data that describes an object at that time ( private attributes)
Behaviour: a set of operation that the object can perform (public methods)
identity: a unique name that identifies an object (object refernce to call its method)
illustrated using Object Diagram
private Within the class Only accessible within the class where it is declared.
Within the package Accessible within the package where it is declared and within
protected
and subclasses subclasses of the class where it is declared.
default Within the package Accessible within the package where it is declared.
Types of Associations
1 / 19
Exam_Notes_-_Application(1).md 5/22/2023
Method Overloading
We can supply several definitions for a method sum within the same class definition, as long as each definition
has different set of input types.
sum(4,5)
sum(4.5,5.5)
sum(4,5,6)
This process is known as static binding, because the decision about which version of the method to apply is
made at the compilation stage.
2 / 19
Exam_Notes_-_Application(1).md 5/22/2023
Question Example: Given the following class definitions, which of the following statements is
correct:
}
}
class Cheese extends Food{
public Cheese{
super(“hello”);
}
}
Answer: Yes it will. The constructor for Food is not explicitly called with super, therefore a no-argument
version will be called implicitly, no such constructor exists (a string argument is expected, so an error will
occur).
Specialisation
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)
Polymorphism: the ability to define methods that can operate on many different types.
When a method is redefined in a hierarchy of classes, and that method is called on an object, the closest
definition (going up the hierarchy from the object's class) is applied, for example:
3 / 19
Exam_Notes_-_Application(1).md 5/22/2023
They (typically) contain at least one abstract method (a prototype method definition with no body)
They cannot be instantiated
Subclasses of the abstract class can be instantiated if they provide full definitions for abstract methods. The
top most levels of a large hierarchy may consist of several abstract classes.
Abstract classes: a class that cannot be instantiated, only inherited from. The inheriting class can use methods
from the abstract class. The abstract class provides a common framework that allowrs subclasses to be
interchanged with other inherting subclasses.
Interfaces: Outline
4 / 19
Exam_Notes_-_Application(1).md 5/22/2023
Question:
Write the code to define an interface called Vehicle which has two methods accelerate and
decelerate that each take a single argument of type int and have a return type void.
interface Vehicle {
public void accelerate(int x);
public void decelerate(int x);
}
Question:
Write the code for a class MotorBike that implements the Vehicle interface and implements
methods for updating the speed of the vehicle defined using a private variable ‘speed’.
@Override
public void accelerate(int val) {
speed += val;
}
@Override
public void decelerate(int val) {
speed -= val;
}
}
GUI applications:
5 / 19
Exam_Notes_-_Application(1).md 5/22/2023
Can take concept one step further by using an anonymous inner class, which has no name and is simply
declared when needed.
Anonymous inner class must either implement an interface or extend an existing class.
Java Swing
Java programs can show Graphical User Interfaces (GUI's)
Swing provides classes and interfaces for presenting GUI elements to the user and allowing interaction.
Swing is able to produce GUIs that look like the platform they're running on.
Swing classes and other components are contained in the javax.swing.package library.
import javax.swing.*;
import java.awt.*;
public class Greeting
{
public void main( String[] args )
{
JFrame frame = new JFrame();
JLabel label = new JLabel("Hello world");
JPanel panel = new JPanel();
panel.add( label, BorderLayout.NORTH );
frame.add( panel, BorderLayout.SOUTH );
frame.setSize( 200, 200 );
frame.setTitle( “Hello” );
6 / 19
Exam_Notes_-_Application(1).md 5/22/2023
}
}
Layout Managers
Layout managers determine the "look" of your application. Components to be placed on an application must
be added to its content pane, their position being determined by a layout manager. The default manager for
applications is BorderLayout
BorderLayout:
Application may have a central component and one on each of four borders, with each component being
placed in a chosen position.
Any components placed on borders will occupy as much space as is needed for the contents; a central
component will occupy all remaining space.
GridBagLayout:
Allows components to be added in any order to specific locations on grid and to straddle multiple locations.
Also allows sizes of rows and columns to vary.
To use, an object of type GridBagConstraints must be created with details of where on the grid a
component is to be placed.
The gridx and gridy in GridBagConstraints object indicate row and column of component.
gridwidth indicates if component should straddle two columns. (To straddle multiple rows we would set the
gridheight value.)
g.setConstraints(l, gbc);
c.add(l);
7 / 19
Exam_Notes_-_Application(1).md 5/22/2023
gbc.gridwidth = 2;
g.setConstraints(t, gbc);
c.add(t);
import javax.swing.*;
import java.awt.*;
Records[] records;
public HealthRecords() {
records = new Records[2];
records[0] = new Referrals();
records[1] = new Vaccinations();
add(panel);
setSize(400, 200);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
8 / 19
Exam_Notes_-_Application(1).md 5/22/2023
The abstract class Records is providing a way to encapsulate elements that are
common to all its subclasses.
The abstract method letterDetails() provides a way for each subclass to provide
its own specific behavior while adhering to the contract established by the
Records class.
Item Listener
9 / 19
Exam_Notes_-_Application(1).md 5/22/2023
Item Listener Works in a similar fashion to action listener, is used for things such as JCheckBox, and Radio
Buttons.
The sequence of methods can be determined by examining the program or input data.
event-driven programming: after 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.
10 / 19
Exam_Notes_-_Application(1).md 5/22/2023
Suitable for Buttons with related functions Buttons that are quite different
A switch statement may be used in actionPerformed to select appropriate action. Extra cases would have to be
added for extra buttons.
Generics/Parameterised Types
Collection classes and interfaces may be parameterised by types, e.g. Collection<\Integer>. Generics can
reduce runtime errors from type errors by allowing abstraction over types.
Code that could throw a checked exception Must implement exception handling
Examples: FileNotFoundException, IOException etc. Unchecked exceptions: Cannot be checked at
compile time.
Code should implement exception handling.
Examples: Error, RuntimeException etc.
Design Patterns
A pattern is a general description of a known problem in software design along with a solution. They derive
from the knowledge and experience of software developers by a process of abstraction that are above the
level of single classes or components.
Elements of a pattern: Pattern name: a meaningful pattern identifier that we can use to describe the
problem, solution, and consequences
Problem: describes when to apply the pattern, sometimes will include conditions that must be met for it to
make sense to apply a pattern Solution: describes the elements that make up the design, their relationships,
responsibilities, and collaborations. A pattern is like a template.
Consequences: the results and trade-offs of applying the pattern such as time/space,
language/implementation issues, impact on system flexibility, ect..
11 / 19
Exam_Notes_-_Application(1).md 5/22/2023
GRASP
General Responsibility Assignment Software Patterns. They describe the fundamental principles of assigning
responsibilities to objects, expressed as patterns
Façade: One class represents the "system" or business that controls everything in the system. Can result
in poor cohesion and high coupling.
Role: one class represents a role (i.e. actor) and controls all the functionality by that actor
Use Case: one class represents one use case and controls the functionality in carrying out that use case
Polymorphism can be achieved by using methods such as subclasses (not trying to fit all use cases into one
class)
12 / 19
Exam_Notes_-_Application(1).md 5/22/2023
JDBC
Allows Java programs to access and manipulate relational databases using SQL statements. The JDBC interface
makes no assumptions about the database other than it can be accessed using SQL.
Once a connection is established, a Statement object must be created to execute SQL statements.
Once we have a statement, it can be used multiple times to perform SQL queries and updates. Queries
are performed using the executeQuery() method which takes a string and returns a ResultSet.
The next() method advances to the next row if it exists, and returns a boolean value detailing if it exists.
getObject() takes one argument indicating the column, and returns the object at that entry. The return
type depends on the type defined in the database.
Connection should be closed once database is no longer needed, this frees up resources. It should be
applied to any statement objects and then the connection object.
13 / 19
Exam_Notes_-_Application(1).md 5/22/2023
Metadata
"Data about data".
Executing Updates
To update a table in database using INSERT, UPDATE, or DELETE statements, simple use executeUpdate() on a
statement object.
Example statements:
Creating/removing tables can be done with the execute() method applied to the statement object.
Prepared Statements
These are parameterised statements that help protect against SQL injections.
Transactions
A group of statements you want to all succeed or none succeed; if some were to succeed, it would leave the
database in an consistent state. CAP = Consistent, Available, Partition Tolerant
Normally individual statements are treated as transactions, this is called auto-commit mode. To
disable/re-enable: connectionObject.autoCommit(bool)
To implement a transaction of multiple statements, disable auto-commit, execute all your statements,
and then use connectionObject.commit() . Be sure to use a try/catch block!
Rollback
If an exception occurs, such as one in a transaction, access should be prevented to the partially processed
database in the current program. Done by calling connectionObject.rollback() , this rolls back to before the
sequence began.
14 / 19
Exam_Notes_-_Application(1).md 5/22/2023
Answer:
try
{
Statement statement = net.createStatement();
ResultSet rs = statement.executeQuery(
“SELECT make, price FROM CarRental”);
while (rs.next())
{
if ( rs.getObject(1).startsWith(srtLet) ){
System.out.print(rs.getObject(1) + " $");
System.out.println(rs.getObject(2));
}
}
}
catch (SQLException e)
{
System.out.println(“database access problem”);
}
15 / 19
Exam_Notes_-_Application(1).md 5/22/2023
You will need to change the "make" and "prices" parameters, as well as the "CarRental" database name.
You will likely also need to change the index of the object in the if statement and the print statement inside
the if statement.
All of the things you need to swap out will be mentioned in the question.
Answer:
**Answer to part (b) of the equalsTo question. Composition is a "has-a" relationship in object-oriented
programming. For example, consider a Parcel class that contains an instance of the Box class. This
16 / 19
Exam_Notes_-_Application(1).md 5/22/2023
means a Parcel "has-a" Box. If the Parcel is destroyed, the associated Box object is also destroyed. This
demonstrates composition, where the lifecycle of the Box is tied to the Parcel.
@Override
public int compareTo(Student otherStudent) {
// Compare based on age
if (this.age < otherStudent.age) {
return -1;
} else if (this.age > otherStudent.age) {
return 1;
} else {
// If ages are equal, compare based on name
return this.name.compareTo(otherStudent.name);
}
}
}
The applet should have two input fields and one output field. It should also have two buttons to start the
calculation. Create two panels.
Add the first panel to the centre of the applet and the second panel to the south. Initialise the three text fields
to have empty contents and lengths 10, 10 and 20, make the output field non-editable and add all three fields
to the first panel.
Create buttons labelled "+" and "-"and add them to the second panel. Associate appropriate action handlers
with the buttons.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class CalculatorApplet extends JApplet {
17 / 19
Exam_Notes_-_Application(1).md 5/22/2023
subtractButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int num1 = Integer.parseInt(input1.getText());
int num2 = Integer.parseInt(input2.getText());
int result = num1 - num2;
output.setText(Integer.toString(result));
}
});
}
}
18 / 19
Exam_Notes_-_Application(1).md 5/22/2023
Question: Briefly discuss the implications of using a separate button handler for each button instead of a
single one Answer: Using separate button handlers for each button promotes code clarity and
maintainability, as it keeps the logic for each action distinct. However, if many buttons share similar
logic or there are a lot of buttons, a single handler could reduce code redundancy and improve
manageability
19 / 19