SEMESTER ONE EXAMINATIONS SOLUTIONS 2004

Similar documents
SEMESTER ONE EXAMINATIONS 2008/2009 SOLUTIONS. Object-Oriented Programming for Engineers - EE553

Question 1. 1(a)(vii) (*prttoobject).somemethod(); Page 1 of 18.

Object-Oriented Programming EE219 Repeat 2004/2005 Page 1 of 8

EE219 - Semester /2009 Solutions Page 1 of 10

EE219 Object Oriented Programming I Repeat Solutions for 2005/2006

EE219 Object Oriented Programming I (2006/2007) SEMESTER 1 SOLUTIONS

EE219 Object Oriented Programming I (2007/2008) REPEAT SOLUTIONS

CONTENTS. Chapter 1 Getting Started with Java SE 6 1. Chapter 2 Exploring Variables, Data Types, Operators and Arrays 13

SEMESTER ONE EXAMINATIONS 2006 SOLUTIONS

EE219 Object Oriented Programming I (2005/2006) SEMESTER 1 SOLUTIONS

Java for Programmers Course (equivalent to SL 275) 36 Contact Hours

Syllabus & Curriculum for Certificate Course in Java. CALL: , for Queries

SEMESTER ONE EXAMINATIONS SOLUTIONS 2003/2004

CS/B.TECH/CSE(New)/SEM-5/CS-504D/ OBJECT ORIENTED PROGRAMMING. Time Allotted : 3 Hours Full Marks : 70 GROUP A. (Multiple Choice Type Question)

SEMESTER ONE EXAMINATIONS 2007 SOLUTIONS. Object-Oriented Programming for Engineers - EE553

Packages: Putting Classes Together

CS/B.TECH/CSE(OLD)/SEM-6/CS-605/2012 OBJECT ORIENTED PROGRAMMING. Time Allotted : 3 Hours Full Marks : 70

Virtualians.ning.pk. 2 - Java program code is compiled into form called 1. Machine code 2. native Code 3. Byte Code (From Lectuer # 2) 4.

Introduction to Java

(c) [5 marks ~1 per point] A virtual machine has several advantages when developing Internet based applications:

Short Notes of CS201

STRUCTURING OF PROGRAM

CS201 - Introduction to Programming Glossary By

VALLIAMMAI ENGINEERING COLLEGE

Multiple Choice Questions: Identify the choice that best completes the statement or answers the question. (15 marks)

Contents. iii Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services August 1998, Revision B

VALLIAMMAI ENGINEERING COLLEGE

15CS45 : OBJECT ORIENTED CONCEPTS

An array is a type of variable that is able to hold more than one piece of information under a single variable name.

Assumptions. History

RAIK 183H Examination 2 Solution. November 11, 2013

DOWNLOAD PDF CORE JAVA APTITUDE QUESTIONS AND ANSWERS

Get Unique study materials from

RAIK 183H Examination 2 Solution. November 10, 2014

B2.52-R3: INTRODUCTION TO OBJECT ORIENTATED PROGRAMMING THROUGH JAVA

Come & Join Us at VUSTUDENTS.net

CS 180 Final Exam Review 12/(11, 12)/08

Introduction... xv SECTION 1: DEVELOPING DESKTOP APPLICATIONS USING JAVA Chapter 1: Getting Started with Java... 1

Table of Contents. Chapter 1 Getting Started with Java SE 7 1. Chapter 2 Exploring Class Members in Java 15. iii. Introduction of Java SE 7...

CS506 Web Programming and Development Solved Subjective Questions With Reference For Final Term Lecture No 1

AP CS Unit 11: Graphics and Events

DUBLIN CITY UNIVERSITY

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

Introduction to Graphical User Interfaces (GUIs) Lecture 10 CS2110 Fall 2008

Object-Oriented Programming

CSC 111, Test 1 (Fall 2009)

Lecture 28. Exceptions and Inner Classes. Goals. We are going to talk in more detail about two advanced Java features:

DHANALAKSHMI SRINIVASAN COLLEGE OF ENGINEERING AND TECHNOLOGY ACADEMIC YEAR (ODD SEM)

C++_ MARKS 40 MIN

Pace University. Fundamental Concepts of CS121 1

SELF-STUDY. Glossary

John Cowell. Essential Java Fast. How to write object oriented software for the Internet. with 64 figures. Jp Springer

1 Shyam sir JAVA Notes

CS Exam 1 Review Suggestions

Java Programming Lecture 6

1 OBJECT-ORIENTED PROGRAMMING 1

SINGLE EVENT HANDLING

DHANALAKSHMI COLLEGE OF ENGINEERING, CHENNAI DEPARTMENT OF ELECTRICAL AND ELECTRONICS ENGINEERING CS6456 OBJECT ORIENTED PROGRAMMING

CS 231 Data Structures and Algorithms, Fall 2016

CS180 Review. Recitation Week 15

Review sheet for Final Exam (List of objectives for this course)

B2.52-R3: INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING THROUGH JAVA

DHANALAKSHMI COLLEGE OF ENGINEERING, CHENNAI DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING REWRAP TEST I CS6301 PROGRAMMING DATA STRUCTURES II

CS180 Spring 2010 Exam 2 Solutions, 29 March, 2010 Prof. Chris Clifton

We are on the GUI fast track path

Multitasking Multitasking allows several activities to occur concurrently on the computer. A distinction is usually made between: Process-based multit

CSE 452: Programming Languages. Previous Lecture. From ADTs to OOP. Data Abstraction and Object-Orientation

Window Interfaces Using Swing Objects

Object Oriented Design

C11: Garbage Collection and Constructors

Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub

20 Most Important Java Programming Interview Questions. Powered by

Java - Applets. public class Buttons extends Applet implements ActionListener

CS201- Introduction to Programming Current Quizzes

CSCI 136 Written Exam #1 Fundamentals of Computer Science II Spring 2015

AN OVERVIEW OF C++ 1

CS 162, Lecture 25: Exam II Review. 30 May 2018

OBJECT ORIENTED PROGRAMMING TYm. Allotted : 3 Hours Full Marks: 70

COMP 2355 Introduction to Systems Programming

Crash Course in Java. Why Java? Java notes for C++ programmers. Network Programming in Java is very different than in C/C++

[CHAPTER] 1 INTRODUCTION 1

1 Looping Constructs (4 minutes, 2 points)

Java Intro 3. Java Intro 3. Class Libraries and the Java API. Outline

Swing - JTextField. Adding a text field to the main window (with tooltips and all)

Recharge (int, int, int); //constructor declared void disply();

MIT AITI Swing Event Model Lecture 17

Java. GUI building with the AWT

Introduction to Programming Using Java (98-388)

CS 6456 OBJCET ORIENTED PROGRAMMING IV SEMESTER/EEE

Object-oriented basics. Object Class vs object Inheritance Overloading Interface

COMS W3101 Programming Language: C++ (Fall 2015) Ramana Isukapalli

Paytm Programming Sample paper: 1) A copy constructor is called. a. when an object is returned by value

public class Foo { private int var; public int Method1() { // var accessible anywhere here } public int MethodN() {

DCS235 Software Engineering Exercise Sheet 2: Introducing GUI Programming

To gain experience using GUI components and listeners.

Queens College, CUNY Department of Computer Science. CS 212 Object-Oriented Programming in Java Practice Exam 2. CS 212 Exam 2 Study Guide

Multithread Computing

C++ 8. Constructors and Destructors

Object Oriented Software Design II

END TERM EXAMINATION

Transcription:

SEMESTER ONE EXAMINATIONS SOLUTIONS 2004 MODULE: Object-Oriented Programming for Engineers EE553 COURSE: M.Eng./Grad. Dip./Grad. Cert. in Electronic Systems M.Eng./Grad. Dip./Grad. Cert. in Telecommunications Engineering RAEC Remote Access to Continuing Eng. Education Question 1. (a) Answer the following short questions. Please keep your answers concise. (i) Why is a destructor virtual in C++? A destructor must be virtual as the destruction of the object must be related to the dynamic type of the object and not the static type. This insures that any dynamic memory or connections open by an object are closed correctly when the object is being destroyed. If the static type destructor was called then the parent destructor would not clean-up the object properly. (ii) What does the super keyword allow in Java? The super keyword allows the child object to access methods of the parent class. This even includes access to the parent constructor. (iii) What are namespaces in C++? Namespaces in C++ are regions of scope that are local to a specific section of the application code. They allow the creation of global functions and variables that will not conflict with functions and variables in another namespace. (iv) When is the garbage collector called in Java? The garbage collector in Java is a daemon thread that counts the references on allocated object, allocating their memory space back to the heap when the object goes out of scope. It is run automatically by the VM when the memory is low, or the CPU is idle. The user can also request that the garbage collector should run. (v) Compare the protected access modifier in C++ to the protected access modifier in Java. Page 1 of 16.

The protected keyword in Java and C++ means that the state or method is accessible in the class and any child classes. However, in Java it also means that the state or method is accessible in the same package. (vi) What does the term over-riding mean? Over-riding means re-writing the same method in a child class, with the exact same set of parameters. Over-riding is a form of polymorphism that allows behaviour to be replaced in a child class. (vii) What is an inline method in C++? An inline method in C++ is a method that is in effect cut-and-pasted into the code, rather than existing as an indexed block of code. An inline method is efficient as the program counter when executing the code does not need to offset and return, rather the instructions are duplicated. This means that the code is efficient, but also becomes larger. [2 marks for each point] (b) What is a copy constructor? What operation does the default copy constructor carry out? Using a small source-code example, demonstrate how a user-defined copy constructor can provide useful functionality. The copy constructor is a special constructor that is automatically a part of every class. It allows a copy to be made of an object. The default copy constructor creates an identical copy of the object, so states have the exact same values. The default copy constructor can be invoked simply by: Account::Account(const Account &sourceaccount): accountnumber(sourceaccount.accountnumber + 1), balance(0.0f), owner (sourceaccount.owner) Account a = Account("Derek Molloy",35.00,34234324); Account b(a); In this case the copy constructor has been modified to copy the account holder name, but to zero the balance of the new account and to set the new account number to be the last one plus 1 (this is not an ideal implementation, just an example). [3 marks description 3 marks source code] (c) Discuss exceptions in Java. Give an example use of exceptions when using arrays in Java. What advantage is there in exception specifications being checked by the Java compiler at compile time? When an error is detected, an exception is thrown. That is, the code that caused the error stops executing immediately, and control is transferred to the catch clause for that exception of the first enclosing try block that has such a clause. The try block might be in the current method (the one that caused the error), or it might be in some method that called the current method (i.e., if the current method is not prepared to handle the exception, it is "passed up" the call chain). If no currently active method is prepared to catch the exception, an error message is printed and the program stops. try // index the array catch (OutOfBoundsException e ) // statements to handle this exception Page 2 of 16.

finally // statements to execute every time this try block executes [3 marks for discussion and 2 marks for code outline] Question 2. (a) Explain the use of over-loaded operators in C++. Why are they a useful feature of the language? C++ allows the programmer to associate specific functionality of a class with the standard predefined operators, such as '+','-','=','==' etc. One class which demonsrates the use of these over-loaded operators is the String class, which associates the '+' with concatenation, '=' to assignment etc. We can over-load the predefined opertors to suit our own classes For example, in the Account class we can add a + operator, allowing Account objects to be summed in an appropriate way. For example: class Account protected: int accountnumber; float balance; string owner; public: Account operator + (Account); ; Account Account::operator + (Account a) return Account(owner, balance + a.balance, accountnumber); [5 marks for description 3 marks for code sample] (b) Write a Colour class in C++ that has the following functionality: The class should contain three states for red, green and blue, each with a range of 0-255. Add appropriate constructors. Is the default copy constructor appropriate? Write overloaded operators for +, -, =, ==, < and >. Write code that checks the bounds on all assignments, i.e. values cannot be <0 or >255. Write a sort segment of code to demonstrate your Colour class in action. Page 3 of 16.

// Colour Example #include<iostream.h> #include<string.h> using namespace std; class Colour private: int red; int green; int blue; void checkbounds(); public: Colour(); Colour(int, int, int); virtual int tograyscale(); virtual int getred() return red; virtual int getgreen() return green; virtual int getblue() return blue; virtual void operator + (Colour); virtual void operator - (Colour); virtual void operator = (Colour); virtual bool operator == (Colour); virtual bool operator < (Colour); virtual bool operator > (Colour); ; virtual void display(); Colour::Colour(): red(0), green(0), blue(0) Colour::Colour(int r, int g, int b): red(r), green(g), blue(b) checkbounds(); void Colour::checkBounds() if (red<0) red=0; if (green<0) green=0; if (blue<0) blue=0; if (red>255) red=255; if (blue>255) blue=255; Page 4 of 16.

if (green>255) green=255; int Colour::toGrayScale() return (int) ( red + green + blue / 3 ); void Colour::operator + (Colour a) red+=a.red; green+=a.green; blue+=a.blue; checkbounds(); void Colour::operator - (Colour a) red-=a.red; green-=a.green; blue-=a.blue; checkbounds(); void Colour::operator = (Colour a) red = a.red; green = a.green; blue = a.blue; checkbounds(); bool Colour::operator == (Colour a) if ((a.red == red) && (a.green == green) && (a.blue == blue)) return true; else return false; bool Colour::operator < (Colour a) if (tograyscale() < a.tograyscale()) return true; else return false; bool Colour::operator > (Colour a) if (tograyscale() > a.tograyscale()) return true; else return false; void Colour::display() cout << "The colour is (r,g,b) = (" << red << "," << green << "," << blue << ")" << endl; void main() Page 5 of 16.

Colour c(220,200,204); c.display(); Colour d(290,100,100); d.display(); if ( c > d ) cout << "C is greater than D!\n"; c.display(); The copy constructor is appropriate. [12 marks] [6 marks for operators, 1 mark per operator] [2 marks for example use] [1 mark for no copy constructor required] [3 marks for constructors and related code] (c) In C++ one class can be a friend of another class, why? Show the coding syntax used to create this relationship, and discuss the advantages and disadvantages of this approach. A class can declare a function or class to be a friend, allowing that function to access private and protected members (friendship is granted! Not acquired.). class A int x; friend class B; public: //methods here ; Friend functions are useful as: Friend functions avoid adding unnecessary public methods to the interface. Prevent states from having to be made public. However, the overuse of friend functions can make the code very complex and hard to follow. [1 marks explain] [2 marks code] [2 mark for adv/disadv] Page 6 of 16.

Question 3. (a) Explain using an example why you would need to synchronize a segment of code when using Java threads? (Your answer should show a line-by-line step through of a segment of code, explaining why it would not work correctly if the segment of code was not synchronized). If synchronization is a solution to making an application thread safe, then why should we not just synchronize all our code? It can be difficult to control threads when they need to share data. It is difficult to predict when data will be passed, often being different each time the application is run. We add synchronization to the methods that we use to share this data like: public synchronized void thesynchronizedmethod() or we can select a block of code to synchronize: synchronized(anobject) This works like a lock on objects. When two threads execute code on the same object, only one of them acquires the lock and proceeds. The second thread waits until the lock is released on the object. This allows the first thread to operate on the object, without any interruption by the second thread. First Thread Second Thread call thesynchronizedmethod() acquires the lock on the theobject executes thesynchronizedmethod on theobject calls thesynchronizedmethod on theobject some other thread has a lock on theobject returns from thesynchronizedmethod() acquires the lock on the theobject Again, synchronization is based on objects: executes thesynchronizedmethod on theobject two threads call synchronized methods on different objects, they proceed concurrently. two threads call different synchronized methods on the same object, they are synchronized. two threads call synchronized and non-synchronized methods on the same object, they proceed concurrently. Static methods are synchronized per class. The standard classes are multithread safe. It may seem that an obvious solution would be to synchronize everything!! However this is not that good an idea as when we write an application, we wish to make it: Safe - we get the correct results Lively - It performs efficiently, using threads to achieve this liveliness These are conflicting goals, as too much synchronization causes the program to execute sequentially, but synchronization is required for safety when sharing objects. Always remove synchronization if you know it is safe, but if you're not sure then synchronize. Page 7 of 16.

[9 marks overall] [4 marks for correct example] [3 marks for intro explain] [2 marks for safety vs. lively] (b) Write a Java egg timer that looks like the application below. Once the start button is pressed the timer will count to two minutes. The timer can be stopped and reset at any time, by pressing stop. When the timer is finished, it should pop-up an appropriate dialog box that states the time is up. // Egg Timer Solution - Derek Molloy import javax.swing.*; import java.awt.*; import java.awt.event.*; import javax.swing.border.*; import java.io.*; import java.applet.*; public class EggTimerApplication extends JFrame implements ActionListener private JProgressBar progressbar; private JButton startbutton, stopbutton; private JLabel textlabel; private EggTimer eggtimer; public EggTimerApplication() super("egg Timer"); JPanel p = new JPanel(); p.setlayout(new BoxLayout(p, BoxLayout.Y_AXIS)); p.setborder(new TitledBorder("Egg Timer:")); progressbar = new JProgressBar(JProgressBar.HORIZONTAL,0,120); JPanel controls = new JPanel(); textlabel = new JLabel(" 0 Seconds "); startbutton = new JButton("Start"); startbutton.addactionlistener(this); stopbutton = new JButton("Stop"); stopbutton.addactionlistener(this); Page 8 of 16.

p.add(progressbar); p.add(textlabel); controls.add(startbutton); controls.add(stopbutton); this.getcontentpane().add("center",p); this.getcontentpane().add("south",controls); this.setsize(300,130); this.show(); this.eggtimer = new EggTimer(this.progressBar, this.textlabel); public void actionperformed(actionevent e) if (e.getsource().equals(startbutton)) this.eggtimer.start(); else if (e.getsource().equals(stopbutton)) this.eggtimer.stoptimer(); public static void main(string[] args) new EggTimerApplication(); class EggTimer extends Thread private int numberseconds = 0; private boolean running = true; private JProgressBar progressreference; private JLabel textlabel; public EggTimer(JProgressBar progressreference, JLabel textlabel) this.progressreference = progressreference; this.textlabel = textlabel; public void run() while(running) if (this.updateprogress()==false) running = false; try Thread.currentThread().sleep(100); Page 9 of 16.

catch (InterruptedException e) System.out.println(e.toString()); private boolean updateprogress() int current = progressreference.getvalue(); int updateto = ++current; if (updateto <= 120) this.progressreference.setvalue(updateto); this.textlabel.settext(" " + updateto + " Seconds "); return true; else this.displaydialog(); return false; public void stoptimer() this.running = false; private void displaydialog() JOptionPane.showMessageDialog(null, "Your Egg is Ready!", "Egg Timer", JOptionPane.INFORMATION_MESSAGE); [16 marks Total Approximate breakdown] [6 for working thread] [4 for user interface] [3 for dialog box] [3 for event structure] Question 4. (a) Compare the C++ language to the Java language under the following headings only: Virtual and non-virtual methods. Access specifiers. Multiple inheritance. (1) In C++ methods are non-virtual by default, so to replace the behaviour (allow over-riding) of a method in the derived class you have to explicitly use the virtual keyword in the parent class. You are able to replace the behaviour of a non-virtual method but this causes serious difficulties when the behaviour of the object depends on Page 10 of 16.

the static rather than the dynamic type! In Java, methods are virtual by default and we always operate on the dynamic type of the object. You cannot specify a method as non-virtual, but there is a final keyword. Once you use the final keyword on a method you cannot replace it - so there are no issues with static and dynamic types. (2) Like C++, in Java we have public, private and protected access specifiers, but we also have another access specifier "package". This is the default access specifier and means that all states and methods are accessible to all classes within the same package. There is no package access specifier keyword, it is simply the default if public, private or protected are not used. Access specifiers in Java are: public - accessible everywhere, an interface method (same as C++) private - accessible only in the class where it was defined (same as C++) protected - accessible in the class where it is defined, the derived classes and in the same package (almost the same as C++ with the exception of the package) "package" - default (there is no package specifier keyword) and means that it is accessible by any class in the same package. You can equate this to the C++ friendly condition by saying that all of the classes in the same package (directory) are friendly. (3) C++ allows multiple inheritance - Java does not! As discussed previously in the C++ section of the notes, multiple inheritance is complex for the programmer, in that they must make complex decisions about the way that the data of the base class is to be inherited. In Java, we do not have multiple inheritance but we do have the use of Interfaces. Interfaces are a special kind of abstract class that have no data or implemented code. Interfaces might not sound too useful, but they allow a form of multiple inheritance, without having the associated difficulties of dealing with data. This replacement behaviour works very well and does not impact on development, once you get used to the change. [9 marks] [3 marks for each point] (b) Use the Java AWT to build the Color Chooser applet below. The applet should allow the user to choose a colour in the range (red,green,blue) of (0-255, 0-255, 0-255) using either the scrollbars or the textfields. // The Colour Chooser Applet Exercise import java.applet.*; import java.awt.*; import java.awt.event.*; Page 11 of 16.

public class ColorChooserApplet extends Applet implements ActionListener, AdjustmentListener private Scrollbar rbar, gbar, bbar; private TextField rfield, gfield, bfield; private ColorCanvas cs; public void init() //For the layout I used a 3x3 grid with the canvas and grid added to FlowLayout Panel rightpanel = new Panel(new GridLayout(3,3)); rightpanel.add(new Label("Red:")); rbar = new Scrollbar(Scrollbar.HORIZONTAL, 128, 10, 0, 265); rbar.addadjustmentlistener(this); rightpanel.add(rbar); rfield = new TextField("128",10); rfield.addactionlistener(this); rightpanel.add(rfield); rightpanel.add(new Label("Green:")); gbar = new Scrollbar(Scrollbar.HORIZONTAL, 128, 10, 0, 265); gbar.addadjustmentlistener(this); rightpanel.add(gbar); gfield = new TextField("128"); gfield.addactionlistener(this); rightpanel.add(gfield); rightpanel.add(new Label("Blue:")); bbar = new Scrollbar(Scrollbar.HORIZONTAL, 128, 10, 0, 265); bbar.addadjustmentlistener(this); rightpanel.add(bbar); bfield = new TextField("128"); bfield.addactionlistener(this); rightpanel.add(bfield); cs = new ColorCanvas(); cs.setsize(100,100); this.add(cs); this.add(rightpanel); this.updatecolor(); // Since no invalid value is possible with the scrollbar error checking is not required. public void adjustmentvaluechanged(adjustmentevent e) rfield.settext(new Integer(rBar.getValue()).toString()); gfield.settext(new Integer(gBar.getValue()).toString()); bfield.settext(new Integer(bBar.getValue()).toString()); this.updatecolor(); //actionperformed is a little complex as the user could type in values //>255 <0 or even enter an invalid string public void actionperformed(actionevent e) Page 12 of 16.

try Integer rval = new Integer(rField.getText()); Integer gval = new Integer(gField.getText()); Integer bval = new Integer(bField.getText()); int rvalint = rval.intvalue(); int gvalint = gval.intvalue(); int bvalint = bval.intvalue(); if(rvalint>=0 && rvalint<=255) rbar.setvalue(rvalint); else throw(new NumberFormatException()); if(gvalint>=0 && gvalint<=255) gbar.setvalue(gvalint); else throw(new NumberFormatException()); if(bvalint>=0 && bvalint<=255) bbar.setvalue(bvalint); else throw(new NumberFormatException()); catch (NumberFormatException nfe) rfield.settext(new Integer(rBar.getValue()).toString()); gfield.settext(new Integer(gBar.getValue()).toString()); bfield.settext(new Integer(bBar.getValue()).toString()); updatecolor(); // I use the scrollbars as storage rather than states private void updatecolor() Color c = new Color(rBar.getValue(), gbar.getvalue(), bbar.getvalue()); cs.updatecolor(c); class ColorCanvas extends Canvas private Color col; public void updatecolor(color c) this.col = c; repaint(); public void paint(graphics g) g.setcolor(col); g.fillrect(0,0,100,100); [16 marks in Total approximate breakdown] [5 marks for the user interface] [3 marks for the canvas class] [6 marks for the event structure] Page 13 of 16.

[2 marks for data/range checking] Question 5. (a) Write a Java client/server banking application pair, where the client passes a Transaction object to the server, the transaction operates on an Account object on the server side, and then returns an appropriate response to the client. The basic transactions to be handled are lodgment, withdrawal, balance enquiry and close account. // The Transaction class - by Derek Molloy [13 marks] import java.net.*; import java.io.*; public class Transaction implements Serializable public static final int LODGEMENT = 1; public static final int WITHDRAWAL = 2; public static final int BALANCEENQ = 3; public static final int CLOSEACT = 4; private int accountnumber; private int transactiontype; private float amount; private String returnmessage = "None"; private boolean successfultransaction = false; public void display() System.out.println("A transaction object"); System.out.println("With Transaction Type: " + transactiontype); System.out.println("With account number: " + accountnumber); System.out.println("With amount: " + amount); public Transaction(int type, int actnum, float amount) this.transactiontype = type; this.accountnumber = actnum; this.amount = amount; public Transaction(int type, int actnum) this(type, actnum, 0.0f); public void setreturnmessage(string s) returnmessage = s; public String getreturnmessage() return returnmessage; public void setreturnsuccess(boolean b) successfultransaction = b; public boolean getreturnsuccess() return successfultransaction; public boolean isforaccount(account a) Page 14 of 16.

if ( a.getaccountnumber() == accountnumber) return true; else return false; public boolean applyto(account a) if (this.transactiontype == Transaction.LODGEMENT) a.makelodgement(amount); else if (this.transactiontype == Transaction.WITHDRAWAL) return a.makewithdrawal(amount); else if (this.transactiontype == Transaction.BALANCEENQ) a.display(); else if (this.transactiontype == Transaction.CLOSEACT) a.close(); else return false; return true; Modifications to Server.java are: [2 marks] break; // create a new thread for the client ConnectionHandler con = new ConnectionHandler(clientSocket, theaccounts); Modifications to HandleConection.java are: [5 marks] private Account[] theaccounts; // The constructor for the connecton handler public ConnectionHandler(Socket clientsocket, Account[] theaccounts) this.clientsocket = clientsocket; this.theaccounts = theaccounts; /** Receive and process incoming command from client socket */ private boolean readcommand() Transaction t = null; try t = (Transaction)is.readObject(); catch (Exception e) t = null; if (t == null) this.closesocket(); Page 15 of 16.

return false; for (int i=0; i<=2; i++) if (t.isforaccount(theaccounts[i])) System.out.println("Applying a transaction"); t.applyto(theaccounts[i]); return true; Modifications to Client.java are: [5 marks] private void dotransactions() Transaction[] trans = new Transaction(Transaction.LODGEMENT, 100001, 1000f), new Transaction(Transaction.BALANCEENQ, 100001), new Transaction(Transaction.WITHDRAWAL, 100001, 50f), new Transaction(Transaction.BALANCEENQ, 100001), new Transaction(Transaction.CLOSEACT, 100001), new Transaction(Transaction.BALANCEENQ, 100001) ; for (int i=0; i<=5; i++) this.send(trans[i]); [25 marks total] Page 16 of 16.