Q1(a) Corrected code is: EE219 Object Oriented Programming I (2005/2006) SEMESTER 1 SOLUTIONS 01 #include <iostream> 02 using namespace std; 03 04 class Question1 05 06 int a,b,*p; 07 08 public: 09 Question1(int x, int y): a(x), b(y) p = &a; 10 Question1(int x): a(x), b(0) p = &a; 11 virtual void display(); 12 virtual int getsum(); 13 virtual ~Question1(); 14 ; 15 16 void Question1::display() 17 cout << "a has value:" << *p << endl; 18 cout << "b has value:" << b << endl; 19 20 21 int Question1::getSum() return a+b; 22 23 Question1::~Question1() 24 cout << "object destroyed" << endl; 25 26 27 int main() 28 29 Question1 q1(5,100), q2(20); 30 q1.display(); 31 cout << "Sum of a + b = " << q1.getsum() << endl; 32 33 q2.display(); 34 cout << "Sum of a + b = " << q2.getsum() << endl; 35 return 0; 36 Line 23 a destructor cannot have a return type, not even void Line 29 q3() cannot be used as there is no default constructor anymore Line 2 should say using namespace std; as cout and endl are currently undefined Lines 8 and 9 should say &a as p is a pointer Line 24 should have around object destroyed as it is a string Line 21 should say return a+b Line 31 cannot say q1.a as it is privately accessible. Line 04 The class keyword is missing Line 13 A destructor must be virtual [18 marks] Q1(b) DCU, student, staff, technician, lecturer, name, address, id, classroom, modules, desks, blackboard, phone, university EE219 - Semester 1 2005/2006 Solutions Page 1 of 9
Create new classes: Persons, Rooms DCU IS-A University DCU has Persons, Rooms, Classroom IS-A Room Has-a Desks, blackboard Office IS-A Room Has-A phone Student IS-A Person Student Has Modules Staff IS-A Person Technician IS-A Staff Lecturer IS-A Staff Lecturer Has Modules Person Has-A name, address, id Students should draw a diagram of these relationships. [7 marks] Q2(a) #include <iostream> #include <string> #include <stdlib.h> using namespace std; class Account float balance; int accountnumber; string owner; static int nextaccountnumber; public: Account(float, string); Account(float); Account(); ; virtual void display(); virtual Account copy(); virtual void makewithdrawal(float &); // verifies amount of withdrawal int Account::nextAccountNumber = 12345; Account::Account(float bal, string name): balance(bal), owner(name) accountnumber = nextaccountnumber++; Account::Account(float bal): balance(bal) accountnumber = nextaccountnumber++; Account::Account(): balance(0.0f) accountnumber = nextaccountnumber++; void Account::display() cout << "Account number: " << accountnumber << " has balance " << balance << " Euro\n"; void Account::makeWithdrawal(float &amt) EE219 - Semester 1 2005/2006 Solutions Page 2 of 9
if ( amt <= balance) balance-=amt; else amt = balance; balance=0; Account Account::copy() return Account(balance, owner); int main() Account a(100.00f), b(200.00f), c; float amt = 600.00f; a.display(); b.display(); b.makewithdrawal(amt); cout << "Amount of withdrawal is " << amt << " Euro" <<endl; b.display(); c = b.copy(); c.display(); system("pause"); return 0; [2 marks for each constructor, 6 total] [2 marks for display] [3 marks for copy] [4 marks for makewithdrawal] [4 marks for main] [19 marks total] Q2(b) An abstract class is a class that is incomplete, in that it describes a set of operations, but is missing the actual implementation of these operations. Abstract classes: Cannot be instantiated. So, can only be used through inheritance. To make the Account class abstract we could write: virtual void display() = 0; (any method would do, even adding one) You would make a class abstract to impose a behaviour on the child classes. You may also wish to prevent a class from being instantiated. Yes it can. [6 marks] EE219 - Semester 1 2005/2006 Solutions Page 3 of 9
3(a) Java has a String class for all string operations. Discuss the following: There are compareto() and equals() methods how do they differ? How do the operators +, = and == affect a String object? Strings are immutable what does this mean? What is the StringBuffer class and how does it differ from the String class? Write a short segment of code to demonstrate the use of the String and StringBuffer classes. compareto() returns an int -1 if the string is less than the compared to String, 0 if the strings are equal and 1 if the string is greater than the compare string. This would return dog is greater than cat. equals() only returns true or false true if the strings are identical + allows for us to concatenate two Strings, == calls the equals() method and = allows us to assign a new String object to the String reference. Strings cannot increase in length. When we use concatenation or any operation that appears to change the size of a String what actually happens is that a new String is created in memory and the reference is assigned to that block of memory. The StringBuffer class is mutable and can change in length. In particular it has an append() method which makes it more suitable for editing operations. 3 import java.lang.*; 4 5 public class StringTest 6 7 public static void main(string args[]) 8 9 String x = "Hello "; 10 String y = new String("World!"); 11 12 String z = new String(x + y); 13 System.out.println(z); 14 System.out.println("The length of this string is " 15 + z.length() + " characters."); 16 17 String c = "Cat"; 18 String d = "Dog"; 19 if (c.compareto(d)<=0) 20 21 System.out.println( c + " is less than " + d); 22 23 24 if (c.equals("cat")) 25 26 System.out.println("The c object is equal to Cat"); 27 28 29 String shout = "HELLO!"; 30 System.out.println("A bit quieter - " + shout.tolowercase()); 31 32 [2 marks for each point] [8 marks] EE219 - Semester 1 2005/2006 Solutions Page 4 of 9
3 import java.lang.*; 4 5 public class StringBufferTest 6 7 public static void main(string args[]) 8 9 String s = new String("Hello World!"); 10 StringBuffer buffer = new StringBuffer(s); 11 12 buffer.insert(5, " to the"); 13 14 String t = buffer.tostring(); 15 System.out.println(t); 16 17 [5 marks] for implementing 5 methods [13 marks] 3(b) A Java Interface is a way of grouping methods that describe a particular behaviour. They allow developers to reuse design and they capture similarity, independent of the class hierarchy. We can share both methods and constants using Interfaces, but there can be no states in an interface. Methods in an interface are implicitly public and abstract. Constant states in an interface are implicitly public, static and final. Interfaces differ from abstract classes in that an interface cannot have an implementation for any method, i.e. all methods are abstract. Classes can implement many interfaces, all unconstrained by a class inheritance structure. interface Demo public static final String democonst = "hello"; // public static final can be omitted // as is implicit [6 marks] void go(); void stop(); // these methods are public and abstract // even if public abstract is omitted class SomeClass extends Object implements Demo public void go() // write implementation here public void stop() // write implementation here public class TestApp EE219 - Semester 1 2005/2006 Solutions Page 5 of 9
public static void main(string args[]) SomeClass c = new SomeClass(); System.out.println(SomeClass.demoConst); // will print out "hello" [6 marks] [12 marks] 4(a) Java applets generally do not have a main() method. What is the lifecycle of a Java applet and what standard methods do we have to write? If we do not write one of these methods will the Applet compile? The life cycle of the applet has the following stages: The appletviewer loads and creates the specified class. The applet initializes itself. The applet starts running. When finished the applet is destroyed. The applet always receives an init() method first and then a start() and paint() call (Note: This may happen asynchronously! i.e. at the same time). init() - This method 'sets-up' the applet, called once when the applet is first initialized. Use this method to set up the display of the applet, set colours etc. start() - Called whenever the applet is visited, i.e. the applet starts running again. You could use this method to start up an animation that stops when the applet is minimised. This method would be called when the web browser has been restored after being minimised. stop() - Called when the applet is no longer active (e.g. minimized) paint()- This method is called whenever the appearance of the applet is required to be updated, such as when the applet is being maximized from a minimized state. The appearance needs to be updated. It is also possible for the programmer to call this method. This method does nothing by default, you must write the code. destroy() - Called when the applet is discarded. This method should perform any closing down tasks that you would wish to perform, such as closing connections to databases, etc. If we do not write one of these methods then the applet will still compile as the method will be inherited from the parent Applet class. [10 marks] 4(b) The JIT compiler reads the bytecode of the Java applet and converts it into native machine instructions for the intended operating system, just after the applet is loaded from the disk. This can happen on a file-by-file basis or even on a method-by-method basis - hence the name, just- EE219 - Semester 1 2005/2006 Solutions Page 6 of 9
in-time. Once the Java applet is converted into native instructions, the application/applet then runs like it was natively compiled. The JIT compiler can, in certain cases, improve the run-time execution speed of applets by a factor of 5-10 times, while still providing portability through retaining the use of intermediate byte-code. Compiled code is kept in memory until the application terminates. [5 marks] 4(c) super - allows us to refer to states and methods of the parent class directly. So, super.display() would call the display() method, written or inherited by the parent class. If the parent class of the parent class with a display() method also had a display() method, we do not have access to that method. This super predefined variable can also be used in an unusual way to call the parent constructor from within the child constructor, provided it is used as the first line of the child constructor (just like member initialisation lists in C++). this - allows us to refer to "this object", i.e. to access states or methods for the class that the code is currently within. It allows us to pass a reference to the current object and it also allows us to access the states of the class that are currently out of scope. So, an example of super and this would be: public class TestParent protected int y=2; // example parent state public TestParent(int a) // example parent constructor y=a; public class Test extends TestParent // inheritance private int x; public Test(int a) super(a); // calls the parent constructor x = 5; public void somemethod(int x) this.x = x; // this.x refers to the state of the class super.y = 5; // sets the y state of the parent class to a value of 5. someothermethod(this); // passes the current object to the // someothermethod() method [6 marks for desc (2 x 3). 4 marks for code] [10 marks] EE219 - Semester 1 2005/2006 Solutions Page 7 of 9
Q5(a) import java.applet.*; import java.awt.*; import java.awt.event.*; public class MouseSolution extends Applet implements MouseListener private AudioClip thesound; private Image theimage; private int x,y; public void init() this.thesound = this.getaudioclip( this.getdocumentbase(), "sound.wav" ); this.theimage = this.getimage( this.getdocumentbase(), "java.gif" ); this.addmouselistener(this); public void mousepressed(mouseevent e) public void mousereleased(mouseevent e) public void mouseentered(mouseevent e) public void mouseexited(mouseevent e) public void mouseclicked(mouseevent e) this.thesound.play(); this.x = e.getx(); this.y = e.gety(); this.repaint(); public void paint(graphics g) g.drawimage(theimage, this.x, this.y, this); <title> Image Applet Page </title> <hr> <applet code=mousesolution.class width=200 height=200> </applet> <hr> [15 marks] [2 for HTML, 4 for stages, 2 for init, 2 for events, 3 for mouseclicked, 2 for paint] Q5(b) Add a canvas class eg.. class MyCanvas extends Canvas EE219 - Semester 1 2005/2006 Solutions Page 8 of 9
public void paint(graphics g) g.drawimage(theimage, this.x, this.y, this);22 Change the paint method in MouseSolution to: public void paint(graphics g) mycanvas.repaint(); Where mycanvas is a member stage of MouseSolution with type MyCanvas. In the init method of MouseSolution add: mycanvas = new MyCanvas(); this.add(mycanvas); mycanvas.setsize(100,100); [10 marks] [4 for MyCanvas class, 3 for state and paint, 3 for init] NB: Many correct solutions to this including inner classes, Canvas event handling etc. EE219 - Semester 1 2005/2006 Solutions Page 9 of 9