Object Oriented Programming Exam - CP 215

University of Dodoma
College of Informatics and Virtual Education
Department of Computer Science and Engineering
End of Semester University Examination for the 2021/2022 Academic Year

Course Name: Object Oriented Programming
Paper Code Number: CP 215
Date of Examination: [Date]
Time: [Time]
Duration: 3 Hours

SECTION A: (15 MARKS)

Question One

  1. Read each question carefully and choose the most correct response. (0.5 Marks Each)

i. What is the connection between public classes and java file names? A. The file must have at least one public class and none of them can have the same name as the file.
B. The file can have at most one public class; if present, it must have the same name as the file.
C. It is common practice to name a file after one of the public classes in it, but Java does not require it.
D. If the file does not contain a public class, its name must not match the names of any of the classes in it.
E. There is no connection!

ii. The static variable declared in a class is called: A. Global variables
B. Local Variables
C. Class variables
D. Instance variables
E. Object variables

iii. Consider the following program:

public class Tour {
    Cathedralistic void main (Strike)
    // Insert a new Cathedralist (left);
    m, etc. code here
    } 90();
}
 
class Catchall {
    class Sanctum {
    void 90()(System.out.println("Spooky");
    }

Which part of code inserted compile and produce the output Spooky?
A. Sanctum m = c.new Sanctum();
B. Sanctum m = c.new Sanctum();
C. Sanctum m = Cathedral.new Sanctum();
D. Cathedral.Sanctum m = c.new Sanctum();
E. Cathedral.Sanctum m = Cathedral.new Sanctum();

iv. Given the following piece of code, What will be printed?

1.class subException extends Exception()
2.class subSubException extends SubException()
3.public class cc { void doStuff() throws SubException();
4.class cc extends cc(void doStuff()throws SubSubException());
5.class cc extends cc { void doStuff() throws Exception();
6.class cc extends cc{ void doStuff(int x)throws Exception ( )}
7.class cc extends cc{ void doStuff() throws SubSubException ( )}

A. Compilation succeeds and nothing is printed
B. Compilation fails due to an error on line 3
C. Compilation fails due to an error on line 5
D. Compilation fails due to an error on line 6
E. Compilation fails due to an error on line 7
F. Compilation fails due to an error on line 8

v. Which of the following statements is true? A. X extends Y is correct if and only if X is a class and Y is an interface.
B. X extends Y is correct if and only if X is an interface and Y is a class.
C. X extends Y is correct for all combinations of X and Y being classes and/or interfaces.
D. X extends Y is correct if X and Y are either both classes and both interfaces.
E. Both C and D


Carefully read the following program and use it to answer questions with that follow: comments indicate where missing components of the program are to be placed.

public class MyMain {
    public static void main(String [ ] args){
    // (2) print the greeting
    // (3) construct a MyClass object called myObject
    // (4) update()
    }
}
 
class MyClass {
    // (1) definition of MyClass constructor
    public static void greetings(){
        // definition of greets
    }
    public void update(int num, String title){
        // definition of update
    }
    public void print(){
        // definition of print
    }
    private int numOfItems;
    private String reportTitle;
}

vi. Suppose you wish to construct MyClass object called myObject at line (3) above. Which of the following statement will correctly do this? A. MyClass myObject.
B. MyClass myObject = MyClass();
C. MyClass myObject = new(MyClass);
D. MyClass myObject = new MyClass();
E. myObject.MyClass();

vii. Suppose you wish to call the method that prints the greeting, at line (2) above. Which of the following statements will call this method correctly? A. myObject.greeting<0;
B. greeting<0;
C. MyClass.greeting<0;
D. Both A and B
E. Both B and C

viii. Suppose you wish to call the update method at line (4) above. Which of the following statements will call this method correctly? A. myObject.update(4,“CP 215”);
B. update(myObject(4,“CP 215”));
C. update(4,“CP 215”);
D. MyClass.myObject.update(4,“CP 215”);
E. MyClass.update(4,“CP 215”);

ix. The following are examples of checked exceptions except: A. SQLException
B. IOException
C. RunTimeException
D. ClassNotFoundException
E. InputMismatchException

x. Assume you have three classes: Person, Teacher, and Student. Teacher and Student are both subclasses of Person. The Person class has P as its object reference; class Teacher has T as its object reference and S being the object reference for Student respectively. Which of these assignment statements are legal? I. S = T
II. P = T
III. T = P
IV. P = S

A. II and IV only
B. II and III only
C. II, III and IV only
D. I, II and IV only
E. I, II, III and IV


Question Two

  1. Match the item in Column A with its corresponding item in Column B. (0.5 Marks Each)
Column AColumn B
i. It is always invoked when a new object is created.A. abstract
ii. The base class for errors and exception.B. Encapsulation
iii. Prevent anyone from instantiating the class directly.C. Inheritance
iv. The method must have access specific or least that of the parent class, and return type, name and identical parameter list.D. Collection of abstract class
v. Each object of Y has an object of XE. Class
vi. The mechanism allows print() and println() methods to invoke toString() method automatically.F. public static void main(String[] args)
vii. Blueprint or template of an object.G. Object
viii. Private members, getter and setter methods.H. Composition
ix. Automatically invoked by JVM.I. Overriding
x. Variables can hold objects of more than one type.J. Polymorphism
K. ArrayLIST
L. unchecked exception
M. checked exception
N. Specialization
O. Instance of class
P. Throwable
Q. Late binding
R. Polymorphism
S. Collection of abstract methods
T. Overloading
V. Interface

Question Three

  1. Answer the following question precisely

a. Some programmers prefer not to use protected access, because they believe it breaks the encapsulation of the superclass. Briefly explain the relative merit of using protected access over private access in superclass. (1 Mark)

b. For each of the following piece of code briefly explain what does it do. (1 Mark Each)

i. Assume the following method call is in an overridden earning method in a subclass:

super.earnings()

ii. Assume the following line of code appears as the first statement in a constructor’s body:

super(firstArgument, secondArgument);

c. The following code contains errors, observe it carefully and rewrite it correctly in your answer booklet. (3 Marks)

public class Circle{
  private double radius;
  public Circle(double radius)
    {radius = radius;}
  public double getRadius(){return radius; }
  public double getArea(){
    return radius * radius * 3.14;}
  class B extends Circle {
    private double length;
    B(double radius, double length) {
    Circle(radius);
    length = length; }
    /** Override getArea() */
    public double getArea() {
    return getArea() * Length;
}

SECTION B: (45 MARKS)

Attempt THREE (3) out of FOUR (4) questions provided.

Question Four

  1. Answer the following questions:

a. What is the source of error in this piece of code? (3 Marks)

class Calculation{
    void sum(int x, int b){system.out.println(x + y);}
    void sum(int a, int b){system.out.println(a + b);}
    public static void main(String args[]) {
    Calculation object = new Calculation();
    object.sum(20, 20);
    }
}

b. Consider book and International Standard Book Number (ISBN) classes. Each book has an ISBN, therefore the relationship between book and ISBN is a Has-A relationship. But if you consider it in the reverse, it would not make sense as it is not necessary for the ISBN to contain a book. Write three classes named ISBN, book and myTester to implement this relationship. The ISBN class consists of 10 digits divided into 4 parts. For example, the ISBN 0 231820 40 5 represent the following information:

The first part: the first digit 0 signifies the book is from an English speaking country.
The second part: 231820 identifies the publisher
The third part: 40 is the title number for the book.
The fourth part: 5 is a check digit to indicate that the sum of the ISBN digits is 10.

The ISBN class should have a constructor and methods to set and get the ISBN as a string. The book class should represent relevant book information including the title, author, publisher, city, date of publication, and price. Also, the class should include constructor and methods such as setbookISBN, getAuthor, getbookISBN, to set the ISBN, return the author of the book and get the ISBN of the book respectively. Furthermore, the book class should have printDetail method to print book information in the following form:

Book Title: Java How to Program
Book Author: Paul Deitel and Harvey Deitel
Publisher: Pearson Education
ISBN: 1 292223 85 5

The class myTester should include main method to test the capability of this relationship and all required data should be supplied from keyboard. **(12 Marks)


Question Five

  1. Answer the following questions:

a. In Java exceptions can be propagated from one method to another. Write a program to illustrate the concept of exception propagation with two methods called myfirst and mySecond. The method myfirst should initially throw an ArlithemeticException exception. The method mySecond should call myfirst method and re-throw the exception. Include a main method that call mySecond method, catch and handle the re-thrown exception, and printing the stack trace of the exception. Include finally block that print exception has been caught message. You do not need to create any object to access these methods. (5 Marks)

b. Carefully read the following requirements and write Java application which implements the specified tasks. Use comments to indicate your implementation on each task.

i. Declare a package called football and add class called FootballTeam make sure your class can be accessed from any package. Also, add the name of the team, number of win and number of losses instance variables into a class FootballTeam, your variables must not be accessed outside of the class. (3 Marks)

ii. Write a constructor that accept the name of the team, the number of wins, and the number of losses as arguments and set the class properties to those values. This constructor should be accessed from any package. (4 Marks)

iii. Write the methods that return the name of the team, the number of wins and the number of losses. These methods should be accessed from any package. Include, also, a method that returns true when a team has a good record. The team will have good record when the number of win is greater than number of losses. This method should be accessible from any package. (6 Marks)

iv. Finally, add a main method to the FootballTeam class. In the main method construct a FootballTeam named “XYCLUB” with 3 wins and 5 losses. Call the method that return true when the team has good record and print out the results. Print also the name of the team, number of wins and losses on the screen. (6 Marks)


Question Six

  1. You are required to write an application that can determine payments for employees and invoices alike, by first creating interface Payable, which contains method getPaymentAmount that returns a double amount that must be paid for an object of any class that implements the interface. Method getPaymentAmount is a general-purpose method to be implemented by classes that implements interface Payable. After declaring interface Payable, introduce class Invoice, which implements interface Payable. We then introduce class Employee that also implements interface Payable. Classes Invoice and Employee both represent things for which the company must be able to calculate a payment amount. Both classes implement the Payable interface, so a program can invoke method getPaymentAmount on Invoice objects and Employee objects alike. This enables the polymorphic processing of Invoices and Employees required for the company’s accounts payable application. Class Invoice represents a simple invoice that contains billing information for only one kind of part. The class declares private instance variables parNumber, partDescription, quantity and pricePerItem. Class Invoice also contains a constructor, get methods and a toString method that returns a String representation of an Invoice object. Class Employee should implement Payable interface. The class contains employee’s firstName, lastName, and employeeID. It also contains a constructor for initialization of instance variable a toString method for returning its string representation. Salaried employee is paid a fixed weekly salary regardless of the number of hours worked. Therefore, SalariedEmployee class should contain a unique variable called salary, a constructor, a toString method for returning its string representation. Figure 1 shows a schematic representation between Payable interface, Invoice, Employee and SalariedEmployee classes. (15 Marks)

Figure 1: Relationship between Interface Payable, class Invoice, Employee and Salaried Employee.


Question Seven

  1. Answer the following questions:

a. You are required to create a Swing GUI application that will convert degree Celsius (°C) to degree Fahrenheit (°F). The application should have a JTextField labeled Celsius, another JTextField labeled Fahrenheit and a JButton named Convert. The application should allow a user to enter degree Celsius on its JTextField and whenever the user clicks Convert button, the application should convert degree Celsius to degree Fahrenheit and display it on Fahrenheit’s JTextField. Use anonymous class in the implementation of event handling. (7.5 Marks)

b. Assume that you have a MySQL database named EmployeeDB running on localhost server and it has a table called EmployeeInfo with four columns: P_id, first_name, last_name and phone_number. Write a Java program that will establish JDBC connection to the database and query the database’s EmployeeInfo table to display first name, last name and phone number of the employees. Exception handling is inevitable for database connectivity, therefor provide try-catch-finally block for exception handling where appropriate. Given the driver class is com.mysql.jdbc.Driver, the port number is 3306. Use root for both username and password. (7.5 Marks)


END OF EXAMINATION PAPER