CS 2136 EXAM 2 December 18, 2003
All five problems count equally.
1. Define each of the following terms in the context of the Java programming language. (One or two sentences each.)
a) inheritance
b) abstract class
c) static method of a class
d) dynamic binding
2. Exceptions
a. When an exception gets thrown, how does Java decide what statement catches it? In other words: Where does Java look for the statement and how does it know which is the right one?
b. What happens if an exception is thrown, and there is no code anywhere in your program to catch it?
c. What does it mean to rethrow an exception?
3. You want to write an applet which has a graphical user interface on which there will be a button. When the button is pressed, some action is taken (you don’t have to actually write the code for the action.)
a) Describe all the steps necessary to create the button and have the action take place when the button is pressed. (No code for this part of the question.)
b) Write Java code to create the button and have the action take place. In place of the code for the actual action, you can just put a comment // some action takes place.
4. Consider these Java class definitions:
class ColdBlood {
String commonName;
String personalName;
}
class Amphibian
extends ColdBlood {
String family;
Amphibian() {
}
Amphibian(String pn) {
personalName
= pn;
}
}
class Frog extends
Amphibian {
String
genus;
String species;
}
Each of the following parts of this question (a., b., c., etc.) contains some Java code, consisting of one or more statements. For each part, answer two questions:
If a part is incorrect, you must say why it is incorrect. Note: This is not a program; each part should be considered separately from all other parts. If a part will not compile, it is okay to answer the second question, “No, it will not run because it will not compile”.
a)
Frog k = new Frog();
k.personalName
= "Jeremiah";
b)
Amphibian a = new Amphibian("Kermit");
a.species
= "Rana";
c)
ColdBlood b;
Frog
g = new Frog();
b = g;
d)
Amphibian d = new Amphibian("Fred");
ColdBlood
c = new ColdBlood();
d
= c;
e)
Amphibian i = new Amphibian("Jeremiah");
ColdBlood
j = new ColdBlood();
i = (Amphibian) j;
5. Write a complete Java class definiton for a class of Weights. Weights should be stored as pounds and ounces. [Hint: There are 16 ounces in a pound.] The pounds can be any non-negative integer. The ounces can be any integer between 0 and 15.
Provide constructors that take 0, 1, or 2 arguments. If there is 1 argument, it will represent the number of pounds. Your constructors must assure that objects are initialized with legal values. If a constructor is presented with illegal values, create a weight with value 0 pounds and 0 ounces.
Provide a method to add two weights. The add method not change the two weights, but return a new Weight object containing the sum.
Provide a method to return the weight in kilograms. [Hint: There are 0.45 kilograms to 1 pound.]
No other methods are required.