COMP 249 - Tutorial #5 - Solution
Abstract Classes & Exceptions
Question 1- What is the result of this program?
public class Inherit
{
abstract class Speaker {
abstract public void speak();
}
class Cat extends Speaker {
public void speak() {
System.out.println("Meow!");
}
}
class Dog extends Speaker {
public void speak() {
System.out.println("Woof!");
}
}
public Inherit() {
Speaker d = new Dog( );
Speaker c = new Cat( );
d.speak( );
c.speak( );
}
public static void main(String[] args) {
new Inherit();
}
}
a. Meow! b.Woof! c.Woof! d. Meow!
Woof! Meow! Woof! Meow!
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.
abstract class MyShape {
abstract double getArea();
}
public class Test {
public static void main(String[] args) {
MyCircle c1= new MyCircle();
c1.setRadius(2.0);
System.out.println(c1);
MyRectangle r1= new MyRectangle();
r1.setHeight(2.0);
r1.setWidth(3.0);
System.out.println(r1);
}
}
Expected result:
Area of this Circle: 12.56
Area of this Rectangle: 6.0
Solution:
public class MyCircle extends MyShape {
double r =0.0;
public double getArea() {
return (3.14 * r * r);
}
public void setRadius(double r) {
this.r = r;
}
public String toString() {
return("Area of this Circle: " + this.getArea());
}
}
public class MyRectangle extends MyShape {
double ht = 0.0;
double wd = 0.0;
public double getArea() {
return (ht*wd);
}
public void setHeight(double ht) {
this.ht = ht;
}
public void setWidth(double wd) {
this.wd = wd;
}
public String toString() {
return("Area of this Rectangle: " + this.getArea());
}
}
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 {
//Define method “TotalArea” here
…………
public static void main(String[] args)
{
MyCircle c1= new MyCircle();
c1.setRadius(2.0);
System.out.println(c1);
MyCircle c2= new MyCircle();
c2.setRadius(3.0);
System.out.println(c2);
MyRectangle r1= new MyRectangle();
r1.setHeight(2.0);
r1.setWidth(3.0);
System.out.println(r1);
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:
public static double TotalArea (MyShape []shapes)
{
double areaSum = 0.0;
for( int i=0; i<shapes.length; i++)
{
areaSum += shapes[i].getArea();
}
return areaSum;
}
Question 3: What is the output of the following program, if the main calls "aMethod();"?
what is main calls "bMethod();"?
class AException extends Exception{
public AException(String msg){
super(msg);
}
}
class BException extends Exception{
public BException(String msg){
super(msg);
}
}
public class Except {
static void aMethod() throws AException, BException
{
throw(new BException("Failed again!"));
}
static void bMethod() throws AException, BException {
try {
aMethod();
}
catch (BException be) {
}
System.out.println("I made it");
}
public static void main(String[] args) throws BException{
try{
//bMethod();
aMethod();
}
catch (AException ae) {
System.out.println(ae.getMessage());
}
finally{
System.out.println("In finally");
}
System.out.println("After finally");
}
}
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...
Question 4: Consider the following program:
public class Test {
public static String l;
/**
* @param args
*/
public static void main(String[] args) {
public static void Test1() {
int[] myArray = new int[5];
for(int i = 0; i <= myArray.length; i++) {
myArray[i] = i;
}
}
public static void Test2() {
double i = 1/0;
i += i;
}
public static void Test3() {
System.out.println(l.length());
}
public static void Test4() {
Object o = new Integer(42);
String l = (String)o;
System.out.println(l.length());
}
public static void Test5() {
System.out.println(Integer.parseInt("12o"));
}
public static void Test6() {
System.out.println(Math.log(-0.123));
}
}
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)
Question 5: Consider the following class.
class Base {
protected void m(int i) {
// some code
}
}
public class Child extends Base {
// 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.
void m(int i) throws Exception {} // not OK... weaker privilege and
should not throw anything
void m(char c) throws Exception {} // OK overloading
public void m(int i) {} // OK
protected void m(int i) throws Exception {} // not OK overriding...
should not throw anything
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 class DivisionByZeroException extends Exception {
public DivisionByZeroException() {
super("Division by zero");
}
public DivisionByZeroException(String errorMsg) {
super(errorMsg);
}
}
import java.util.Scanner;
import java.io.IOException;
public class DivisionByZero {
public static void main(String[] args) throws IOException
{
Scanner keyboard = new Scanner(System.in);
try {
System.out.println("Enter numerator:");
int numerator = keyboard.nextInt();
System.out.println("Enter denominator:");
int denominator = keyboard.nextInt();
double quotient = safeDivide(numerator, denominator);
System.out.println(numerator + "/" + denominator + " = " + quotient);
}
catch(DivisionByZeroException e) {
System.out.println(e.getMessage());
secondChance();
}
}
public static double safeDivide(int top, int bottom) throws
DivisionByZeroException
{
if (bottom == 0)
throw new DivisionByZeroException();
return top/(double)bottom;
}
public static void secondChance() throws IOException
{
Scanner keyboard = new Scanner (System.in);
try {
System.out.println("Try again - Enter numerator:");
int numerator = keyboard.nextInt();
System.out.println("Enter denominator:");
int denominator = keyboard.nextInt();
double quotient = safeDivide(numerator, denominator);
System.out.println(numerator + "/" + denominator + " = " + quotient);
}
catch (DivisionByZeroException e) {
System.out.println("I cannot do division by zero.");
System.out.println("Aborting program.");
System.exit(0);
}
}
}