COMP 249 - Tutorial #5 - Solution Abstract Classes & Exceptions
COMP 249 - Tutorial #5 - Solution Abstract Classes & Exceptions
public Inherit() {
Speaker d = new Dog( );
Speaker c = new Cat( );
d.speak( );
c.speak( );
}
Solution: b
Question 2 In this question, we create a base class MyShape to provide a method to return the
area of 2-D shapes represented by class MyRectangle and class MyCircle.
Area of Rectangle = height*width;
Area of Circle = 3.14*radius*radius;
2.1. Define the classes MyRectangle and MyCircle to correspond to the classes MyShape and
Test below and the expected result provided below.
Expected result:
Area of this Circle: 12.56
Area of this Rectangle: 6.0
Solution:
2.2. Rewrite the class MyShape without using abstract class. This new class MyShape should be
still match classes Test, MyRectangle and MyCircle and the expected result.
Solution:
public class MyShape {
double getArea() {
return 0.0; }
}
2.3. The capability to reference instances of MyRectangle and MyCircle as MyShape types
brings the advantage of treating a set of different types of shapes as one common type. Define a
method TotalArea in the class Test in order to get the result as below.
public class Test {
MyShape shapes[]={c1,c2,r1};
// We are using the “TotalArea” method here
System.out.println("Total Area is: " + TotalArea(shapes));
}
}
Expected result:
Area of this Circle: 12.56
Area of this Circle: 28.26
Area of this Rectangle: 6.0
Total Area is: 46.82
Solution:
Question 3: What is the output of the following program, if the main calls "aMethod();"?
what is main calls "bMethod();"?
with aMethod:
In finally
Exception in thread "main" BException: Failed again!
at Except.aMethod(Except.java:16)
at Except.main(Except.java:31)
with bMethod:
I made it
In finally
After finally
Press any key to continue...
Given the above program, if the main method were run 6 times, each time using a different Test,
which tests would produce which RuntimeExceptions?
a. ArithmeticException (Test2)
b. NumberFormatException (Test5)
c. NegativeArraySizeException
d. NullPointerException (Test3)
e. ArrayIndexOutOfBoundsException (Test1)
f. NoException (Test6)
g. ClassCastException(Test4)
class Base {
protected void m(int i) {
// some code
}
}
// Method Here
}
For each of the following methods, indicate if it can or cannot be legally inserted in place of
the comment //Method Here. If a method cannot be inserted, briefly explain why not.
Question 6:
Write a method called safeDivide that takes 2 integers num and denum, checks for a
possible division by zero and throws a DivisionByZero exception if it is the case.
Use your method safeDivide to divide 2 integers entered by the user entered on the
screen. If there is a 1st attempt at dividing by zero, we give the user a 2nd chance. After
the 2nd chance, we quit the program.
public DivisionByZeroException() {
super("Division by zero");
}
import java.util.Scanner;
import java.io.IOException;