Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
26 views19 pages

Exam Notes - Application1 1

Uploaded by

Louis Cross
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
26 views19 pages

Exam Notes - Application1 1

Uploaded by

Louis Cross
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 19

Exam_Notes_-_Application(1).

md 5/22/2023

Object Orientated Concept


A class represents a type of entity

defines the entity's data (attributes) & operations (methods)

illustrated using class diagram.

Objects are instances of a class

An object is a run-time program entity that has

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

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 object)
The state of an object is given by the values of its instance variables.

Scope and Scope modifiers: Overview


Modifier Access Description

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.

public Everywhere Accessible everywhere, even outside the package.

Types of Associations

1 / 19
Exam_Notes_-_Application(1).md 5/22/2023

Object Orientation : Composition & Specialisation

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.

int sum (int i, int j)


{return i + j;}

double sum (double e, double f)


{return e + f;}

int sum (int i, int j, int k)


{return i + j + k;}

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:

public class Shape{ ... }


public class Circle extends Shape{ ... }
public class Cylinder extends Square { ... }

[A] Shape roundThing = new Cylinder(...);

Inheritance: super example

public class Food{


public Food( String Type ){

}
}
class Cheese extends Food{
public Cheese{
super(“hello”);
}
}

Question Example: Will this code cause an error?

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

Specialisation hierarchies and Interfaces are closely related topics.

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)

Specialisation - Dynamic Binding

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

Abstract Classes : Overview

Abstract classes are partial specifications

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

public interface MediaPlayer {


public void stop();
public void play();
public void rewind (double rSpeed)
public void forward (double fSpeed)
public int pause();
}

public class DVDPlayer implements MediaPlayer {


public int speed;

4 / 19
Exam_Notes_-_Application(1).md 5/22/2023

public void rewind( int rs )


{
speed -= rs;
}

public void forward( int fs )


{
speed = fs;
}
}

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’.

class MotorBike implements Vehicle {


private double speed = 0;

@Override
public void accelerate(int val) {
speed += val;
}

@Override
public void decelerate(int val) {
speed -= val;
}
}

Anonymous Inner Classes : Overview

GUI applications:

An inner class that implements ActionListener often has just 1 object;


Created and passed as an argument to the addActionListener method.

5 / 19
Exam_Notes_-_Application(1).md 5/22/2023

Object effectively anonymous - no variale in program refers to it.

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.

public class WeatherStationInterface extends JFrame {


WeatherStation weather;
public WeatherStationInterface(){
weather = new WeatherStation
}

JButton SetTemp = new JButton(“Set Temperature”);


SetTemp.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
weatherStation.setTempValue();
}
}
});

Java Swing
Java programs can show Graphical User Interfaces (GUI's)

Swing is a GUI toolkit.

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.

A Swing application running on windows will look like a windowrs application


(Can also use plugins to create GUIs that looks unrelated to their environment)

Swing classes and other components are contained in the javax.swing.package library.

import javax.swing.*; //import Swing 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.

setConstraints() applies constraints to manager before add().

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.)

GridBagLayout g = new GridBagLayout();


c.setLayout(g);

GridBagConstraints gbc = new GridBagConstraints();

JLabel l = new JLabel("Hello");


gbc.gridx = 0;
gbc.gridy = 0;

g.setConstraints(l, gbc);
c.add(l);

JButton b = new JButton("b1");


gbc.gridx = 1; // gridy still 0
g.setConstraints(b, gbc);
c.add(b);

JTextField t = new JTextField(20);


gbc.gridy = 1; // gridx still 1

7 / 19
Exam_Notes_-_Application(1).md 5/22/2023

gbc.gridwidth = 2;
g.setConstraints(t, gbc);
c.add(t);

Question Example: Using anonymous inner classes, add event listeners to


allow the buttons to respond to user presses by calling the
‘letterDetails()’ method.

import javax.swing.*;
import java.awt.*;

public class HealthRecords extends JFrame {

Records[] records;

public HealthRecords() {
records = new Records[2];
records[0] = new Referrals();
records[1] = new Vaccinations();

JButton butR = new JButton("Referrals");


JButton butV = new JButton("Vaccinations");

JPanel panel = new JPanel();


panel.add(butR, BorderLayout.WEST);
panel.add(butV, BorderLayout.EAST);

GridBagLayout gbl = new GridBagLayout();


setLayout(gbl);

GridBagConstraints gbc = new GridBagConstraints();


gbc.gridx = 1;
gbc.gridy = 1;
gbl.setConstraints(panel, gbc);

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

HealthRecords rc = new HealthRecords();


}
}
abstract class Records {
String letter;
abstract void letterDetails();
}
class Referrals extends Records {
public Referrals() {
letter = "appointment date, patient Id, specialist name";
}
void letterDetails() {
System.out.println("Referral: " + letter);
}
}
class Vaccinations extends Records {
public Vaccinations() {
letter = "appointment date, location, vaccine name";
}
void letterDetails() {
System.out.println("Vaccination " + letter);
}
}

Adding event listener

JButton butR = new JButton("Referrals");


butR.addActionListener(e -> {
records[0].letterDetails();
});
JButton butV = new JButton("Vaccinations");
butV.addActionListener(e -> {
records[1].letterDetails();
});

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.

The significance of both of these features is that it allows for polymorphism


throughout the code.

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.

Event vs Procedural programming.


procedural programming: methods call other methods.

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.

Impossible to determine order of methods by inspecting code.

10 / 19
Exam_Notes_-_Application(1).md 5/22/2023

Handling Multiple buttons information.


Multiple Event Handler
Single Event Handler Object
Objects

Suitable for Buttons with related functions Buttons that are quite different

Memory usage Uses less memory Uses more memory

Code Can lead to complex/hard to maintain Code can be more


complexity/maintainability code straightforward

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.

Exceptions: checked vs unchecked


Checked exceptions: Checked at compile time.

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

Expert maintains encapsulation, supports low coupling and high cohesion.

Creator supports low coupling. (Watch for aggregates, contains, records)

High Cohesion means classes should represent single concepts

Low Coupling means minimal dependencies across classes (aids scalability)

Controller has three types:

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.

Communication to the database is by Strings containing SQL statements


Communication from the database is in rows of a ResultSet

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".

Can be applied to the ResultSet: ResultSetMetaData md = rs.getMetaData();


Then can get information such as column count, name, types of objects, ect..
int count = md.getColumnCount();
String columnName = md.getColumnName();
Database Meta Data allows you to retrieve data from the database itself, such as database product
name, types of tables supported, driver name, ect..

Executing Updates
To update a table in database using INSERT, UPDATE, or DELETE statements, simple use executeUpdate() on a
statement object.

Example statements:

INSERT INTO my_table (columnName1, columnName2) VALUES (value1, value2)


DELETE FROM my_table WHERE columnName1 = "myString"
UPDATE my_table SET columnName2 = value2 WHERE columnName1 = "myString"

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.

Call the prepareStatement method on the connection object.


The parameter should be the statement to be executed; question marks are placeholders.
Substitute the placeholders with desired values using the corresponding setXXX method - The first
parameter is the index of the placeholder, second the value

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

SQL Database question


Question: Assume that we have a database table called CarRental and that it holds three columns: vehicle
make (the name of a rental vehicle, of type string), number available to rent an integer, and daily rental price
(a double), and that we have already successfully connected to the database with a connection object
referenced by the variable net. Write some code that will extract and list the makes and prices of all vehicles
that begin with a specific letter (you can assume the letter is already available in a variable named strl.et, of
type string). The output should be in the following format and your code should handle exceptions.

Honda CRV $25.20

Hyundai Tucson $26.95

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

^^^ notes for above

You may need to change .net or variable net.

You will need to change the "make" and "prices" parameters, as well as the "CarRental" database name.

You will also need change the "srtLet" in the if statement.

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.

Add additional row question.


Question: Imagine you want to add a new item to the list of available vehicles. Write a method to insert an
additional row into the database containing the new vehicle, its' rental price, and an initial number available to
rent. The method should take three parameters (the make, price, and number) and insert these into the
database. As before you may assume the connection to the database has already been established and is
referenced by the variable net.

Answer:

public void addNewVehicle( String make, double price, int number ) {


String cmd = "INSERT INTO CarRental " +
"VALUES (" + make + ",'" number +
"'," price +")";
try {
Statement statement = conn.createStatement();
statement.executeUpdate(cmd);
}
catch( SQLException e ) {
System.out.println( "database access problem" );
}
}

Override equals example

public boolean equals(Object o)


{
return (this.length == o.length && this.height == o.height && this.width ==
o.width);
};

**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.

Overide CompareTo example

public class Student implements Comparable<Student> {


private String name;
private int age;

public Student(String name, int age) {


this.name = name;
this.age = age;
}

// Getters and setters

@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);
}
}
}

Basic Calculator applet example


Question: (A) Write a simple calculator applet that allows a user to perform addition or subtraction of two
integer numbers.

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

JTextField input1, input2, output;


JButton addButton, subtractButton;

public void init() {


// Setup layout
setLayout(new BorderLayout());
JPanel panel1 = new JPanel();
panel1.setLayout(new FlowLayout());
add(panel1, BorderLayout.CENTER);
JPanel panel2 = new JPanel();
panel2.setLayout(new FlowLayout());
add(panel2, BorderLayout.SOUTH);

// Initialize text fields


input1 = new JTextField(10);
input2 = new JTextField(10);
output = new JTextField(20);
output.setEditable(false);

// Add text fields to panel1


panel1.add(input1);
panel1.add(input2);
panel1.add(output);

// Create and add buttons to panel2


addButton = new JButton("+");
subtractButton = new JButton("-");
panel2.add(addButton);
panel2.add(subtractButton);

// Add action handlers


addButton.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));
}
});

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

You might also like