COMP200 Exam Prep SOLUTIONS
1.9) b) Class Zebra generates a compiler error. Find the reason why this is the case.
2.1)
2.1.1) Overloaded methods and constructors let you use the same method name (or
constructor) but with different argument lists. Overloaded methods must change the
argument list, they can change the return type and the access modifier. A method
can be overloaded in the same class or in a subclass.
Overriding lets you redefine a method in a subclass when you need new subclass
specific behaviour. The argument list and the return type must exactly match that of the
overridden method. The access level must not be more restrictive than that of the
overridden method.
2.1.2) In single inheritance, a class is allowed to extend only one base class while in
multiple inheritance, a class may extend more than one base class.
2.2)
2.2.1) A method is polymorphic if the action performed by the method depends on the
actual type of the object to which the method is applied. Different objects can respond
to the same message in different ways.
2.2.2) Generic PROGRAMMING refers to writing code that will work for many types
of data for example sort routines.
2.2.3) Are per-class methods. They are associated with the class and not objects. They
cannot reference instance variables or methods.
d) Inner classes in Java are classes defined within the scope of another class. They have access
to the members (including private members) of the outer class. Inner classes are often used to
logically group classes that are only used in one place, to increase encapsulation, and to
improve readability and maintainability of code.
Anonymous inner classes are a special type of inner class that are declared and instantiated all
in one statement using the new keyword. They are typically used when you need to create an
instance of a class with certain "one-time" modifications, especially for implementing
interfaces or extending a class in a concise manner.
//Give examples of Inner and Anonymous class
e) Java's layout managers are used in GUI programming to control the arrangement and sizing
of components within containers. They provide a flexible way to create complex and resizable
user interfaces without needing to specify exact pixel positions and sizes, which can vary with
different screen sizes and resolutions. Layout managers handle the positioning and resizing of
components automatically, making it easier to develop cross-platform applications.
//Give examples of each layout and explain how it operates
2.4 Checked exceptions describe a problem that is likely to occur at times,
no matter how careful you are not your fault. They are normally due
to external failures beyond your control, such as deleted file, server
crashing, network outage, etc. ClassNotFoundException, IOException,
EOFException, FileNotFoundException, UnknownHostException.
The compiler insists you handle checked exceptions those that you
cannot prevent
Unchecked exceptions fall under the RunTimeException class and are
due the fault of the programmer, RunTimeException, ArrayIndex-
OutOfBoundsException, ArithmeticException, NullPointerException,
ClassCastException. You are not compelled to handle checked exceptions.
1)a) Encapsulation – it is one of the fundamental principles of object-oriented programming
(OOP). It refers to the bundling of data (variables) and methods (functions) that operate on the
data into a single unit, or class. It restricts direct access to some of the object's components,
which can help prevent the accidental modification of data. This is typically achieved using
access modifiers like private, protected, and public.
b) Inheritance - is a mechanism wherein a new class (subclass or derived class) inherits the
properties and behaviour (fields and methods) of an existing class (superclass or base class).
This allows for code reuse and the creation of a hierarchical relationship between classes.
c) Polymorphism - means "many shapes" and allows objects to be treated as instances of their
parent class rather than their actual class. The most common use of polymorphism in Java is
through method overriding and method overloading.
d) Abstract methods - is a method that is declared without an implementation (without braces,
and followed by a semicolon), within an abstract class. Abstract methods must be overridden
in subclasses.
e) Interfaces - in Java is a reference type, similar to a class, that can contain only constants,
method signatures, default methods, static methods, and nested types. Interfaces cannot contain
instance fields and cannot provide any method implementations. Classes that implement an
interface must provide implementations for all the methods declared in the interface.
1 Question 1
1.1) Illegal - You cannot instantiate an interface directly. Interfaces in Java cannot be
instantiated because they are abstract by nature. An object must be created from a concrete
class that implements the interface.
1.2) Legal - si is an instance of SubImplementer, which implements MyInterface. Therefore, it
can be assigned to a variable of type MyInterface. This is an example of polymorphism.
1.3) Legal - si is an instance of SubImplementer, which is a subclass of SuperClass. Thus, a
SubImplementer object can be assigned to a SuperClass variable.
1.4) Illegal - sub is an instance of SubClass, which extends SuperClass but does not implement
MyInterface. Therefore, sub cannot be assigned to a variable of type SubImplementer, which
requires the object to be both a SuperClass and implement MyInterface
1.5) Illegal - Even though sub is a SubClass, the cast (SuperClass)s will not help because s is
not a SubClass. s is declared as SuperClass and assigning it to sub directly without ensuring
that s actually references a SubClass instance will cause a ClassCastException at runtime. The
assignment needs a cast to SubClass rather than SuperClass.
Question 5
5.1 Green. paintComponent draws the rectangle in whatever colour the variable “colour”
is currently set to. “Colour” is initialised to green. So, before any action like clicking
on the panel or pressing a button, green is the colour in which the rectangle will be
drawn.
5.2 Red. Clicking inside the rectangle changes the variable “colour” to red, and a repaint
is thereafter done. So, the rectangle colour will change to red.
5.3 By setting the variable “colour” to yellow in the button listener, the program obviously
intends for the rectangle to change to yellow when the button is pressed. In fact it won’t,
because there is no “repaint()” statement to force a redraw to make the colour change
take effect on the screen. We must therefore put in a repaint() statement.
Note that the rectangle might still change to yellow at some stage. This would occur if
some other part of the program issues a repaint() without “colour” having been changed,
or if we take some action which achieves the same effect. For example, suppose we press
the button and then resize the window in which the rectangle is located. This will cause
a redraw of the screen, and the rectangle will change to yellow! It might seem as though
resizing the window is the cause of the rectangle changing colour. In reality, it is just a
completely unintended side-effect, arising because of the earlier bug of leaving out the
repaint in the button listener
5.4 It does any drawing in the super class of the panel in which it is located. In this case,
we could actually leave it out and the code would still work. But it’s very bad practice
to do so, since it makes our code vulnerable to bugs if and when it gets changed. For
example, if we wanted to make a background colour for the panel, we might do this in
the constructor.
5.5 The MouseAdapter class is a convenience class which provides a dummy implementation
of all the methods in the MouseListener interface. Since in a particular application we
very often actually only require one or two of the methods in the interface, it’s easier to
extend MouseAdapter and just override those methods that we do need, rather than to
do a full implementation of the interface. Were we to implement the MouseListener
interface fully ourselves, those methods that we didn’t need would no doubt just have
dummy implementations anyway.
Here we only need the mouseClicked method, so we extend MouseAdapter and just
override mouseClicked.
5.6 Test2Panel() {
// Use an anonymous inner class for the button's action listener
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
colour = Color.MAGENTA;
repaint();
});
addMouseListener(new ClickListener());
add(button);
Question 3 (11 Marks)
a) The first call to a.speak() outputs "Animal speaks" because a is an instance of Animal.
The second call to a.speak() outputs "Oink-oink" because a is now an instance of Pig and Pig
overrides the speak method.
The third call to b.speak() outputs "Oink-oink" because b is an instance of Pig and calls its
overridden speak method.
b) Animal a = new Pig();
This statement will compile and execute correctly. A Pig is a subclass of Animal, so a Pig object
can be assigned to a variable of type Animal.
Pig c = a;
This statement will not compile. The reference a is of type Animal, which is a superclass of
Pig. Java does not allow implicit downcasting from a superclass to a subclass. An explicit cast
is required.
Lion d = (Lion) a;
This statement will compile but fail at runtime with a ClassCastException
The reference a points to an instance of Pig, not Lion. Trying to cast a Pig instance to Lion will
cause a ClassCastException at runtime because Pig and Lion are not related classes (they do
not share a parent-child relationship).
c) The Animal class will not compile if you try to create an instance without providing a name
because there is no default constructor available.
Both the Pig and Lion classes will compile correctly as long as they call one of the constructors
of Animal from their own constructors, either explicitly or implicitly.
Question 4 ( 15 Marks)
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class CarPanel extends JPanel {
private int carX; // x-coordinate of the car
private boolean isMoving; // flag to track if the car is currently moving
private Timer timer; // Timer for animation
public CarPanel() {
setBackground(Color.LIGHT_GRAY); // Set light grey background
carX = 0; // Initial position of the car
isMoving = true; // Initially, the car is moving
// Create a timer to animate the car
timer = new Timer(20, new ActionListener() {
public void actionPerformed(ActionEvent e) {
moveCar(); // Move the car every 20 milliseconds
});
timer.start(); // Start the timer
addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
if (e.getX() > carX) {
// Clicked to the right of the car, stop the car
isMoving = false;
} else {
// Clicked to the left of the car, start the car
isMoving = true;
});
protected void paintComponent(Graphics g) {
super.paintComponent(g);
drawCar(g, carX, getHeight() / 2 - 20); // Draw the car
}
private void drawCar(Graphics g, int x, int y) {
g.setColor(Color.RED);
g.fillRect(x, y, 50, 40); // Draw the car as a rectangle
g.setColor(Color.BLACK);
g.drawRect(x, y, 50, 40); // Draw the outline of the car
private void moveCar() {
if (isMoving) {
carX++; // Move the car to the right
if (carX > getWidth()) {
carX = -50; // Reset the car position to the left edge when it reaches the right edge
repaint(); // Repaint the panel to update the car's position
public static void main(String[] args) {
JFrame frame = new JFrame("Car Animation");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 200);
frame.add(new CarPanel());
frame.setVisible(true);
Question(20 Marks)
Class: Client
Attributes:
Name (String)
Address (String)
Telephone number (String)
List of accounts (List<Account>)
Methods:
Constructor(s)
Getter and setter methods for attributes
Method to perform transactions on accounts
Method to request the balance on any account
Subclasses:
BusinessClient
Inherits from Client.
Additional Attribute:
VAT number (String)
Additional Functionality:
Method to assign or change a client services adviser.
IndividualClient
Inherits from Client.
Additional Attribute:
Annual income (double)
Additional Functionality:
Method to check if the client is a premium client and allocate a personal banker if applicable.
Class: Account
Description: Represents a bank account.
Attributes:
Account number (String)
List of transactions (List<Transaction>)
Balance (double)
Methods:
Constructor(s)
Getter and setter methods for attributes
Method to perform transactions (deposit or withdrawal)
Method to generate a monthly statement
Subclasses:
ChequeAccount
Inherits from Account.
Additional Functionality:
None
SavingsAccount
Inherits from Account.
Additional Attributes:
Withdrawal limit (int)
Interest rate (double)
Additional Functionality:
Method to calculate interest and update balance monthly.
DepositAccount
Inherits from Account.
Additional Attributes:
Deposit period (int)
Interest rate (double)
Additional Functionality:
Method to prevent withdrawals during the deposit period.
Method to calculate interest and update balance monthly.
Class: Transaction
Description: Represents a transaction on a bank account.
Attributes:
Transaction date (Date)
Account number (String)
Amount (double)
Transaction type (Deposit or Withdrawal)
Methods:
Constructor(s)
Getter and setter methods for attributes
Class: PersonalBanker
Description: Represents a personal banker assigned to premium individual clients.
Attributes:
Name (String)
Employee ID (String)
Methods:
Constructor(s)
Getter and setter methods for attributes
Method to provide personalized banking services to clients
Class: ClientServicesAdviser
Description: Represents a client services adviser assigned to business clients.
Attributes:
Name (String)
Employee ID (String)
Methods:
Constructor(s)
Getter and setter methods for attributes
Method to provide client services to business clients
5 Question 5
public class NegativeValueException extends Exception {
private double errorValue;
public NegativeValueException(double errorValue) {
super("Negative value: " + errorValue);
this.errorValue = errorValue;
}
public double getErrorValue() {
return errorValue;
1 Question 1
1.1) b) A, B, C, and D will be printed
1.2) d) public void xyz(float f)
1.3) e) line 5
1.4) b) B
1.5) c) i and iii only
1.6) d) d
1.7) c) Value is 5This value is 6
1.8) c) 16.0