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

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

EE219 - Semester /2009 Solutions Page 1 of 10

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

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

EE219 Object Oriented Programming I Repeat Solutions for 2005/2006

SEMESTER ONE EXAMINATIONS SOLUTIONS 2003/2004

PESIT Bangalore South Campus

Java Mouse Actions. C&G criteria: 5.2.1, 5.4.1, 5.4.2,

An applet is a program written in the Java programming language that can be included in an HTML page, much in the same way an image is included in a

CSIS 10A Practice Final Exam Solutions

HAS-A Relationship. Association is a relationship where all objects have their own lifecycle and there is no owner.

Inheritance, and Polymorphism.

User interfaces and Swing

CS 120 Fall 2008 Practice Final Exam v1.0m. Name: Model Solution. True/False Section, 20 points: 10 true/false, 2 points each

1. Java is a... language. A. moderate typed B. strogly typed C. weakly typed D. none of these. Answer: B

CSIS 10A PRACTICE FINAL EXAM Name Closed Book Closed Computer 3 Sheets of Notes Allowed

Get Unique study materials from

Homework 6. Yuji Shimojo CMSC 330. Instructor: Prof. Reginald Y. Haseltine

S.E. Sem. III [CMPN] Object Oriented Programming Methodology

MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question.

Java Applets. Last Time. Java Applets. Java Applets. First Java Applet. Java Applets. v We created our first Java application

Chapter 1 GUI Applications

Lecture Static Methods and Variables. Static Methods

Example: Count of Points

Assumptions. History

HAS-A Relationship. Association is a relationship where all objects have their own lifecycle and there is no owner.

Road Map. Introduction to Java Applets Review applets that ship with JDK Make our own simple applets

CE221 Programming in C++ Part 1 Introduction

Brief Summary of Java

CMSC 341. Nilanjan Banerjee

Answer1. Features of Java

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

HAS-A Relationship. If A uses B, then it is an aggregation, stating that B exists independently from A.

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

Lecture Static Methods and Variables. Static Methods

Practice Questions for Final Exam: Advanced Java Concepts + Additional Questions from Earlier Parts of the Course

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)

UCLA PIC 20A Java Programming

3.Constructors and Destructors. Develop cpp program to implement constructor and destructor.

Java Identifiers, Data Types & Variables

G51PRG: Introduction to Programming Second semester Applets and graphics

Object Oriented Design Final Exam (From 3:30 pm to 4:45 pm) Name:

Inheritance. Benefits of Java s Inheritance. 1. Reusability of code 2. Code Sharing 3. Consistency in using an interface. Classes

Government Polytechnic, Muzaffarpur. Name of the Lab: OBJECT ORIENTED PROGRAMMING

L4,5: Java Overview II

Instance Members and Static Members

Java Object Oriented Design. CSC207 Fall 2014

Constructor - example

Introduction Of Classes ( OOPS )

INTRODUCTION TO COMPUTER PROGRAMMING. Richard Pierse. Class 9: Writing Java Applets. Introduction

Class definition. complete definition. public public class abstract no instance can be created final class cannot be extended

1 Shyam sir JAVA Notes

2 rd class Department of Programming. OOP with Java Programming

Selected Questions from by Nageshwara Rao

Homework 5. Yuji Shimojo CMSC 330. Instructor: Prof. Reginald Y. Haseltine

CS 231 Data Structures and Algorithms, Fall 2016

Accurate study guides, High passing rate! Testhorse provides update free of charge in one year!

G52CPP C++ Programming Lecture 13

Outline. Java Models for variables Types and type checking, type safety Interpretation vs. compilation. Reasoning about code. CSCI 2600 Spring

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

1 Definitions & Short Answer (5 Points Each)

Object Oriented Programming (OOP) is a style of programming that incorporates these 3 features: Encapsulation Polymorphism Class Interaction

CS 376b Computer Vision

UNIVERSITI TEKNIKAL MALAYSIA MELAKA FACULTY INFORMATION TECHNOLOGY AND COMMUNICATION (FTMK) BITE 1513 GAME PROGRAMMING I.

User-built data types Mutable and immutable data

Example: Count of Points

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

Modern C++ for Computer Vision and Image Processing. Igor Bogoslavskyi

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

Programming overview

More About Objects. Zheng-Liang Lu Java Programming 255 / 282

Function Overloading

Packages & Random and Math Classes

Polymorphism CSCI 201 Principles of Software Development

COMP-202. Objects, Part III. COMP Objects Part III, 2013 Jörg Kienzle and others

Object Oriented Design

ITI Introduction to Computing II

Java Applet & its life Cycle. By Iqtidar Ali

Selected Java Topics

STRUCTURING OF PROGRAM

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

JAVA: A Primer. By: Amrita Rajagopal

Object Oriented Software Design II

Kapil Sehgal PGT Computer. Science Ankleshwar Gujarat

Object Oriented Software Design II

Program Fundamentals

DUBLIN CITY UNIVERSITY

Windows and Events. created originally by Brian Bailey

Introduction to Java

Lecture-5. Miscellaneous topics Templates. W3101: Programming Languages C++ Ramana Isukapalli

Polymorphism Part 1 1

CS 6456 OBJCET ORIENTED PROGRAMMING IV SEMESTER/EEE

ITI Introduction to Computing II

Exercise: Singleton 1

Extending Classes (contd.) (Chapter 15) Questions:

COMP 2355 Introduction to Systems Programming

CE221 Programming in C++ Part 2 References and Pointers, Arrays and Strings

Programming Languages and Techniques (CIS120)

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

Lecture 5: Java Graphics

Transcription:

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