PROGRAMME: BSc HONOURS DEGREE IN COMPUTER SCIENCE
COURSE CODE AND TITTIE: HCS 124 OBJECT ORIENTED PROGRAMMING
NAME AND SURNAME: EMMANUEL MLAMBO
REG NUMBER: M206393
ENTRY TYPE: CONVENTION
LEVEL: 1.2
ASSIGNMENT NUMBER: 01
LECTURE: DR P. SAMBO
COMMENTS………………………………………………………………………………………
1 i) What are the advantages of OOP programming over functional programming.
[10]
Faster development-Reuse enables faster development. Object-oriented
programming languages come with rich libraries of objects, and code developed
during projects is also reusable in future projects
Effective problem solving-OOP languages allows you to break down your software into
bite-sized problems that you then can solve one object at a time.
Flexibility through polymorphism-a single function can shape-shift to adapt to
whichever class it’s in, you could create one function in the parent Car class for example
“drive” — not “driveCar” or “driveRaceCar,” but just “drive.” This one function would
work with the RaceCarDriver, LimousineDriver in the case of cars. In fact, you could
even have “raceCar.drive(myRaceCarDriver)” or “limo.drive(myChauffeur).”
Modularity for easy troubleshooting-hen working with object-oriented programming
languages, you know exactly where to look. “Oh, the car object broke down? The
problem must be in the Car class!” You don’t have to muck through anything else.
Objects are self-contained, and each bit of functionality does its own thing while leaving
the other bits alone.
Reuse of code through inheritance- you can create one generic class (Car), and then
define the subclasses (RaceCar and Limousine) that are to inherit the generic class’s
traits, although , Limousine and RaceCar still have their unique attributes and functions.
Encapsulation-oop allows us to create objects of a certain class , oop programming
languages have a way to protect variables from outside access, forcing programmers to
only interact with the class through specific method and this provides us security,
encapsulation is also an advantage in that it helps us to make flexible code that is easy to
change and maintain.
ii) With code examples explain use of vector clocks in Java.
[10]
A vector clock is used for determining the partial ordering of events in a distributed
system. It enabling users to determine the flow of potential causality in a system. Just
as in Lamport timestamps, inter-process messages contain the state of the sending
process's logical clock. A vector clock of a system of N processes is an array/vector
of N logical clocks. . Each logical clock is stored as a map of <ProcessID, Time> pairs. A
process increments its time in a logical clock when a relevant event occurs. A process
includes its vector clock in all messages that are sent between processes in the
distributed system. Thus, when communication occurs between two processes in the
system, the processes compare and consolidate vector clocks by taking an element-wise
maximum
Example code
package com.mups;
public class Vectorclock{
public int [] v;
int my ID;
int N;
public VectorClock(int numProc, int id) {
myID=id;
N=numProc;
v=new int[numProc];
for (int i=1; i<N; i++)v[i]=0;
v[myID]=id;
}
public void tick[]{
v[myID]++;
}
public void sendAction(){
v[myid]++;
}
public void receiveAction(int[] sentValue) {
for (int i=0; i<N;i++)
v[i]=Util.max(v[i], sentValue[i]);
v[myid]++;
}
}
1. Write a java program that will be able to connect to MySQL database and be able to
write the following on the database (users), reg_no, module, name, surname, gender,
year of study.
[20]
package com. muchanyu;
import java. sql. Connection;
import java. sql. DriverManager;
import java. sql. SQLException;
import java. sql. Statement;
public class JavaMySQLExe {
public static void main (String[] args){
String url = "jdbc:mysql://localhost:3306/namdb";
String username "mups";
String passworg "triple3411";
try{
Connection connection = DriverManager.getConection(url, usernme, password);
String sql = "INSERT INTO users(reg no, module, name, surname, gender, year
of study) VALUES(?, ?, ?, ?, ?, ?)";
PreparedStatement statement = connection.prepareStatement(sql);
statement.setString (1, M206393);
statement.setString (2, oop);
statement.setString (3, Emmanuel);
statement.setString (4, Mlambo);
statement.setString (5, male);
statement.setString (6, 2021);
int rows = statement.executeUpdate();
if (rows > 0){
System.out.println("A row has been inserted");
}
Statement.close();
Connection.close();
} catch (SQLException){
System.out.println(" ERROR OCCURED!");
printStackTrace();
}
}
}
2. Write a program with class “Shape” that will be able to calculate the area and
perimeter of a rectangle.
[20]
package com.mups;
import java.util.Scanner;
public class Shape {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("enter your length");
double length = sc.nextDouble();
System.out.println("Enter your width");
double width = sc.nextDouble();
double Area= length*width;
double perimeter =(length+width)*2;
System.out.println("Your Area is "+Area+" and your perimeter is "+perimeter);
}
}
3. Draw a class diagram showing a student, course and class relationship. [20]
4. i) Describe the types of Java interfaces and how the original interfaces contained
abstract methods and static final fields. How did this restriction avoid the complexities
of extending multiple classes?
[10]
Interface is a mechanism to achieve abstraction in Java. Interface is similar to abstract
class but having all methods of abstract type, (ie) it cannot have a method body.
Since Java 8, we can have default and static methods in an interface.
Since Java 9, we can have private methods in an interface.
Types of interfaces
1 Marker interface -> is an interface without any method.
2 Single Abstract Method (SAM) -> it has only one method.
3 Normal
Java interface
It is used to achieve abstraction.
By interface, we can support the functionality of multiple inheritance.
It can be used to achieve loose coupling.
The original interfaces has no need to show the abstract and public key words because
Java interface already read a method as public abstract.
When writing fields, no need to write these key words, public, static and final because
Java interface already read fields as public static final
FOR EXAMPLE
Interface InterfaceName
{
method // abstract, public.
eg), public abstract void show();
fields // public, static and final.
eg), public static fnal int a = 10;
}
Example
Interface I1
{
void show ();
}
class Test implements I1;
{
public void show ();
{
System. out. println ("hello");
}
public static void main (String[] args);
}
Test t = new Test();
t. show();
}
}
ii) Explain concurrent queuing in Java with example code. [10]
A concurrent queue is basically a queue which provides protection against multiple threads mutating its
state and thus causing inconsistencies. A naive way to implement a concurrent queue may be to just slap
locks in its enquirer and dequirer functions when they try to modify the head and tail. In multithreaded
applications, queues need to handle multiple concurrent producers-consumer’s scenarios. The correct
choice of a concurrent queue could be crucial in achieving good performance in our algorithms.
Firstly, we'll see some important differences between a blocking queue and a non-blocking one.
Then, we'll take a look at some implementations and best practices
Differences between blocking and non-blocking queue
Blocking queue offers a simple thread-safe mechanism. In this queue, threads need to wait for
the queue's availability. The producers will wait for available capacity before adding elements,
while consumers will wait until the queue is empty. In those cases, the non-blocking queue will
either throw an exception or return a special value, like null or false. To achieve this blocking
mechanism, the blocking queue interface exposes two functions on top of the normal queue
functions: put and take. Those functions are the equivalent of add and remove in a standard
queue.
Concurrent Queue Implementations
Concurrent Linked Queue
Concurrent Linked Queue is an unbounded thread-safe queue which arranges the element in
FIFO. New elements are added at the tail of this queue and the elements are added from the head
of this queue. Concurrent Linked Queue class and its iterator implements all the optional
methods of the Queue and Iterator interfaces. The Concurrent Linked Queue is the only non-
blocking queue of this guide. Consequently, it provides a “wait-free” algorithm where add and
poll are guaranteed to be thread-safe and return immediately. Instead of locks, this queue uses
CAS (compare and swap)
import java.util.concurrent.*;
public class ConcurrentLinkedQue {
int element = 1;
ExecutorService executorService =
Executors.newFixedThreadPool(2);
ConcurrentLinkedQueue<Integer>queue = new
ConcurrentLinkedQueue<>();
Runnable offerTask = () ->queue.offer(element);
Callable<Integer>pollTask = () -> {
while (queue.peek() != null) {
return queue.poll().intValue();
}
return null;
};
executorService.submit(offerTask);
Future<Integer>returnedElement =
executorService.submit(pollTask);
assertThat(returnedElement.get().intValue(),
is(equalTo(element)));
}
Linked Blocking Queue
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
public class LinkedListQue {
ExecutorService executorService =
Executors.newFixedThreadPool(1);
LinkedBlockingQueue<Integer>queue = new LinkedBlockingQueue<>();
executorService.submit() -> {
try {
queue.take();
}
catch (InterruptedException e) {
// exception handling
}
};
}