OOP - Object Oriented Programming, Past Papers

Object Oriented Programming BSSE & IT 2nd Term 2016 Past Paper UOS

University of Sargodha BS 2nd Term 2016 Object Oriented Programming exam question paper

University of Sargodha
BS 2nd Term Examination 2016
Subject: I.T & Software Engineering
Paper: Object Oriented Programming (CMP:2123)
Time Allowed: 2:30 Hours
Maximum Marks: 60

Objective Part (Compulsory)

Q1. Write short answers of the following in 2-3 lines each. (2*12)

  1. Does Java support Multiple Inheritance?
  2. What is Polymorphism?
  3. What is Object Serialization?
  4. What is the purpose of finally() block?
  5. Can a constructor be overloaded?
  6. Can one try block have multiple catch blocks?
  7. Differentiate between abstract class and concrete class?
  8. What is this keyword and its purpose? Give an example?
  9. Can we override Static Methods if not why?
  10. What is Wrapper class in java?
  11. What is meant by Standard System Exception? Give two examples.
  12. What packages does java provide for graphics programming?

Subjective Part (4*9=36)

Note: Attempt any four questions. All questions carry equal marks.

Q2. Create a class publication (title, price). Create two classes named books (no of pages) and tape (playing time) from it. Write appropriate constructors, print() and get() functions for each class. Write an application that demonstrates using objects of each class.

Q3. Create an abstract Auto class with fields for the car make and price. Include get and set methods for these fields; the setPrice() method is abstract. Create two subclasses for individual automobile makers (for example Mehran, Toyota) and include appropriate setPrice() methods in each class (i.e. Rs 600000 or Rs 1800000). Finally, write an application that uses Auto class and subclasses to display information about different cars.

Q4. Write down a class Time having fields (hrs, mins, secs), containing no argument constructor, three argument constructor and copy constructor. Also write down a method inc_time() that increments seconds by 1 if seconds are equal to 60 then increment minute by 1 and set seconds to 0. If minutes become equal to 60 then increment hrs by 1 and set minutes to 0. Write down a method that compares two time objects and return true if they are equal else returns false.

Q5. Create a class Rational having fields (num, denum). Include two argument constructor, get() and print() methods. get() should throw exception if entered denominator is zero. Finally, write an application that uses Rational class. Instantiate two objects and then call get() and display method for each object.

Q6. a) What is Composition? Explain your answer with example. [5]
b) What is this keyword and its purpose. Give an example. [4]

Q7. Write a program that counts the number of times a particular character occurs in a text file. Your program should prompt for the character.

Solved answers

All programs are in Java, as the paper asks about Java.

Q1 – Short questions

(i) Does Java support multiple inheritance? Not with classes — a class can extend only one class, to avoid ambiguity (the “diamond problem”). Java achieves multiple inheritance of type through interfaces: a class can implement many interfaces.

(ii) Polymorphism: the ability of one name or reference to take many forms. Compile-time polymorphism is method overloading; run-time polymorphism is method overriding, where a superclass reference calls the subclass version of a method.

(iii) Object serialization: converting an object’s state into a byte stream so it can be saved to a file or sent over a network, and later rebuilt (deserialization). The class must implement java.io.Serializable.

(iv) Purpose of the finally block: code in finally always runs after try/catch, whether an exception occurs or not. It is used for clean-up such as closing files, streams or database connections.

(v) Can a constructor be overloaded? Yes. A class can have several constructors with different parameter lists, e.g. a no-argument constructor and a two-argument constructor.

(vi) Can one try block have multiple catch blocks? Yes. Each catch handles a different exception type; more specific exceptions must come before general ones (e.g. ArithmeticException before Exception).

(vii) Abstract vs concrete class: an abstract class is declared with abstract, can contain abstract methods without bodies and cannot be instantiated. A concrete class has bodies for all its methods and objects can be created from it.

(viii) this keyword: this refers to the current object. It is used to tell fields apart from parameters with the same name, to call another constructor of the same class (this(...)) and to pass the current object. Example: this.name = name;

(ix) Can we override static methods? No. Static methods belong to the class, not to objects, and are resolved at compile time. A subclass can declare a static method with the same signature, but that is method hiding, not overriding.

(x) Wrapper class: a class that wraps a primitive value in an object — Integer for int, Double for double, Character for char, etc. Needed for collections and utility methods; Java converts automatically (autoboxing/unboxing).

(xi) Standard system exceptions: exceptions predefined in the Java library and thrown by the JVM, e.g. ArithmeticException (divide by zero) and ArrayIndexOutOfBoundsException; others are NullPointerException and NumberFormatException.

(xii) Packages for graphics programming: java.awt, javax.swing and java.awt.geom (JavaFX in newer versions).

Q2 – Publication, Book and Tape classes

import java.util.Scanner;

class Publication {
    protected String title;
    protected double price;
    Scanner sc = new Scanner(System.in);

    Publication() { title = ""; price = 0; }
    Publication(String title, double price) { this.title = title; this.price = price; }

    void get() {
        System.out.print("Enter title: ");
        title = sc.nextLine();
        System.out.print("Enter price: ");
        price = Double.parseDouble(sc.nextLine());
    }
    void print() {
        System.out.println("Title: " + title + ", Price: " + price);
    }
}

class Book extends Publication {
    private int pages;
    Book() { super(); pages = 0; }
    Book(String t, double p, int pages) { super(t, p); this.pages = pages; }
    void get() {
        super.get();
        System.out.print("Enter number of pages: ");
        pages = Integer.parseInt(sc.nextLine());
    }
    void print() {
        super.print();
        System.out.println("Pages: " + pages);
    }
}

class Tape extends Publication {
    private double playingTime;   // in minutes
    Tape() { super(); playingTime = 0; }
    Tape(String t, double p, double time) { super(t, p); playingTime = time; }
    void get() {
        super.get();
        System.out.print("Enter playing time (minutes): ");
        playingTime = Double.parseDouble(sc.nextLine());
    }
    void print() {
        super.print();
        System.out.println("Playing time: " + playingTime + " min");
    }
}

public class PublicationDemo {
    public static void main(String[] args) {
        Book b = new Book();
        Tape t = new Tape();
        b.get();
        t.get();
        b.print();
        t.print();
    }
}

Q3 – Abstract Auto class with Mehran and Toyota subclasses

abstract class Auto {
    protected String make;
    protected double price;

    Auto(String make) { this.make = make; }
    public String getMake() { return make; }
    public void setMake(String make) { this.make = make; }
    public double getPrice() { return price; }
    public abstract void setPrice();      // each maker sets its own price
}

class Mehran extends Auto {
    Mehran() { super("Mehran"); setPrice(); }
    public void setPrice() { price = 600000; }
}

class Toyota extends Auto {
    Toyota() { super("Toyota"); setPrice(); }
    public void setPrice() { price = 1800000; }
}

public class AutoDemo {
    public static void main(String[] args) {
        Auto[] cars = { new Mehran(), new Toyota() };
        for (Auto a : cars) {
            System.out.println("Make: " + a.getMake() + "  Price: Rs " + a.getPrice());
        }
    }
}

Q4 – Time class

class Time {
    private int hrs, mins, secs;

    Time() { hrs = 0; mins = 0; secs = 0; }                 // no-argument
    Time(int h, int m, int s) { hrs = h; mins = m; secs = s; } // three-argument
    Time(Time t) { hrs = t.hrs; mins = t.mins; secs = t.secs; } // copy constructor

    void inc_time() {
        secs++;
        if (secs == 60) {
            secs = 0;
            mins++;
            if (mins == 60) {
                mins = 0;
                hrs++;
            }
        }
    }

    boolean isEqual(Time t) {
        return hrs == t.hrs && mins == t.mins && secs == t.secs;
    }

    void show() {
        System.out.println(hrs + ":" + mins + ":" + secs);
    }
}

public class TimeDemo {
    public static void main(String[] args) {
        Time t1 = new Time(10, 59, 59);
        Time t2 = new Time(t1);    // copy
        t1.inc_time();
        t1.show();                 // 11:0:0
        System.out.println("Equal? " + t1.isEqual(t2));   // false
    }
}

Q5 – Rational class that throws an exception for a zero denominator

import java.util.Scanner;

class Rational {
    private int num, denum;
    Rational(int n, int d) { num = n; denum = d; }

    void get() throws Exception {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter numerator: ");
        num = sc.nextInt();
        System.out.print("Enter denominator: ");
        int d = sc.nextInt();
        if (d == 0)
            throw new Exception("Denominator cannot be zero");
        denum = d;
    }

    void print() {
        System.out.println(num + "/" + denum);
    }
}

public class RationalDemo {
    public static void main(String[] args) {
        Rational r1 = new Rational(1, 2);
        Rational r2 = new Rational(3, 4);
        try {
            r1.get();
            r1.print();
            r2.get();
            r2.print();
        } catch (Exception e) {
            System.out.println("Error: " + e.getMessage());
        }
    }
}

Q6 (a) – Composition

Composition is a “has-a” relationship in which a class contains objects of other classes as its fields, and the contained objects cannot exist meaningfully without the container. It is a strong form of association. Example: a Car has an Engine.

class Engine {
    int horsePower;
    Engine(int hp) { horsePower = hp; }
}

class Car {
    private String model;
    private Engine engine;              // Car HAS-A Engine
    Car(String model, int hp) {
        this.model = model;
        engine = new Engine(hp);        // created inside Car
    }
    void show() {
        System.out.println(model + " with " + engine.horsePower + " hp engine");
    }
}

Q6 (b) – this keyword with example

this is a reference to the current object. Uses: to refer to instance variables when parameters have the same names, to call another constructor of the same class, and to pass or return the current object.

class Student {
    String name;
    int age;
    Student(String name, int age) {
        this.name = name;    // field = parameter
        this.age = age;
    }
    Student(String name) {
        this(name, 18);      // calls the other constructor
    }
}

Q7 – Count occurrences of a character in a text file

import java.io.*;
import java.util.Scanner;

public class CharCount {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter file name: ");
        String fileName = sc.nextLine();
        System.out.print("Enter character to count: ");
        char target = sc.nextLine().charAt(0);

        int count = 0;
        try (FileReader fr = new FileReader(fileName)) {
            int ch;
            while ((ch = fr.read()) != -1) {
                if ((char) ch == target)
                    count++;
            }
            System.out.println("'" + target + "' occurs " + count + " times.");
        } catch (FileNotFoundException e) {
            System.out.println("File not found: " + fileName);
        } catch (IOException e) {
            System.out.println("Error reading file: " + e.getMessage());
        }
    }
}

Answers prepared by Shining Study for revision. Check them against your class notes and teacher’s guidance.

About Saif R

An educator and technology enthusiast passionate about empowering students through quality education and digital learning. Dedicated to making academic resources and opportunities accessible to everyone.