"); document.writeln("Name: " + studentName + "
"); document.write("Score: " + numCorrect + " / " + numPossible + " (" + scorePercent + "%)"); if (numSubjective > 0) { document.write("     [" + numSubjective + " subjective "); if (numSubjective == 1) document.write("question"); else document.write("questions"); document.write(" not graded]"); } document.writeln("

"); document.writeln("
" + titleString + "

"); document.writeln(""); currentInstruction = 0; currentNarrative = 0; for (i=0; i < numQuestions; ++i) { if (currentInstruction < numInstructions) { if (instructionIndex[currentInstruction] == i) { document.writeln(""); ++currentInstruction; } } if (currentNarrative < numNarratives) { if (narrativeIndex[currentNarrative] == i) { document.writeln(""); ++currentNarrative; } } document.writeln(""); document.writeln(""); document.writeln(""); document.writeln(""); } document.writeln("

"); document.writeln(instructionText[currentInstruction]); document.writeln("
 
"); document.writeln("
"); document.writeln(narrativeText[currentNarrative]); document.writeln("
 
"); document.writeln("
" + prefixText[i] + "

" + numberText[i] + " 

" + questionText[i]); document.writeln("

"); document.writeln(""); if (listMap.charAt(i) != "1") { document.writeln(""); document.writeln(""); } document.writeln(""); document.writeln(""); if (showNotes) { document.writeln(""); document.writeln(""); } if (showRef) { document.writeln(""); document.writeln(""); } document.writeln("

RESPONSE: 

" + responseText[i] + "

ANSWER: 

" + answerText[i] + "

NOTES: 

" + notesText[i] + "

REF: 

" + refText[i] + "
"); document.writeln("
 
"); document.writeln("
"); document.writeln(""); document.writeln(""); document.write(""); document.writeln("
 
"); document.writeln("Retake Test"); document.write(""); document.writeln("Help"); document.writeln("
"); document.writeln(""); document.writeln(""); document.close(); return(false); } function GetResponse(answerIndex, answer) { var listIndex; var responseText; if (listMap.charAt(answerIndex) == "1") { listIndex = answer.selectedIndex; responseText = answer.options[listIndex].text; } else responseText = answer.value; return(responseText); } function ScoreAnswer(answerIndex, responseText) { var listIndex; var answerText; answerText = ansMap[answerIndex]; if (qtypeMap.charAt(answerIndex) == "4") return(NumericCompare(responseText, answerText)); else if (qtypeMap.charAt(answerIndex) == "5") return(MultiCompare(responseText, answerText)); else if (responseText.toUpperCase() == answerText.toUpperCase()) return(true); else return(false); } function BuildPrefixText(answerIndex, responseText, isCorrect) { var text; var listIndex; text = "
"
		if (isCorrect)
			text += ""
		else
			text += ""

		if (listMap.charAt(answerIndex) == "1") {
			if (responseText.length == 0)
				responseText = " ";
			text += " " + responseText + " ";
		}

		text += "
" return(text); } function StripSpaces(s) { var len; var i; len = s.length; for (i=len - 1; i >= 0 && s.charAt(i) == " "; --i) len = i; if (len == 0) s = ""; else if (len != s.length) s = s.substring(0, len); return(s); } function TranslateHtmlString(text) { var newText; var replaceString; var position; var length; var breakPos; var skipExtra; var i; newText = ""; position = 0; length = text.length; while (position < length) { skipExtra = 0; breakPos = -1; for (i=position; i < length && breakPos < 0; ++i) { switch(text.charAt(i)) { case '>': replaceString = ">"; breakPos = i; break; case '<': replaceString = "<"; breakPos = i; break; case '&': replaceString = "&"; breakPos = i; break; case '\r': if ((i + 1) < length && text.charAt(i + 1) == '\n') skipExtra = 1; replaceString = "
"; breakPos = i; break; case '\n': replaceString = "
"; breakPos = i; break; case ' ': if ((i + 1 < length) && text.charAt(i + 1) == ' ') { replaceString = " "; breakPos = i; } break; } } if (breakPos < 0) { newText += text.substring(position, length); position = length; } else { if (breakPos > position) newText += text.substring(position, breakPos); newText += replaceString; position = breakPos + 1 + skipExtra; } } return(newText); } function FixMCNotes(notesText, studentText) { var displayText; var searchText; var upperNotes; var charCode; var startIndex; var endIndex; displayText = ""; if (studentText.length > 0 && notesText.length > 0) { upperNotes = notesText.toUpperCase(); studentText = studentText.toUpperCase(); charCode = studentText.charCodeAt(0); searchText = "/" + String.fromCharCode(charCode) + "/"; startIndex = upperNotes.indexOf(searchText); if (startIndex >= 0) { startIndex += searchText.length; searchText = "/" + String.fromCharCode(charCode + 1) + "/"; endIndex = upperNotes.indexOf(searchText, startIndex); if (endIndex < startIndex) endIndex = notesText.length; displayText = notesText.substring(startIndex, endIndex); } else if (notesText.charAt(0) != "/") displayText = notesText; } return(displayText); } function NumericCompare(s1, s2) { var s1Sign; var s2Sign; var tempString; var decimalCount; var decimalPos; var numToDelete; var len; var ch; var i; s1.toUpperCase(); s2.toUpperCase(); if (s1 == s2) return(true); else { s1Sign = 1; s2Sign = 1; tempString = ""; for (i=0; i < s1.length; ++i) { ch = s1.charAt(i); if (ch == "-" && tempString.length == 0) s1Sign = -1; else if ((ch >= "0" && ch <= "9") || ch == ".") tempString += ch; } s1 = tempString; decimalCount = 0; decimalPos = -1; for (i=0; i < s1.length; ++i) { if (s1.charAt(i) == '.') { ++decimalCount; if (decimalPos < 0) decimalPos = i; } } if (decimalCount == 1 && decimalPos >= 0) { len = s1.length; for (i=len - 1; i >= decimalPos; --i) { if (i == decimalPos || s1.charAt(i) == '0') len = i; else break; } if (len < s1.length) s1 = s1.substring(0, len); if (s1.length == 0) s1 = "0"; } numToDelete = 0; for (i=0; i < s1.length; ++i) { if (s1.charAt(i) == "0") ++numToDelete; else break; } if (numToDelete > 0) { if (numToDelete == s1.length) --numToDelete; if (numToDelete > 0) s1 = s1.substring(numToDelete); } ///////////////////////////////////////////// tempString = ""; for (i=0; i < s2.length; ++i) { ch = s2.charAt(i); if (ch == "-" && tempString.length == 0) s2Sign = -1; else if ((ch >= "0" && ch <= "9") || ch == ".") tempString += ch; } s2 = tempString; decimalCount = 0; decimalPos = -1; for (i=0; i < s2.length; ++i) { if (s2.charAt(i) == '.') { ++decimalCount; if (decimalPos < 0) decimalPos = i; } } if (decimalCount == 1 && decimalPos >= 0) { len = s2.length; for (i=len - 1; i >= decimalPos; --i) { if (i == decimalPos || s2.charAt(i) == '0') len = i; else break; } if (len < s2.length) s2 = s2.substring(0, len); if (s2.length == 0) s2 = "0"; } numToDelete = 0; for (i=0; i < s2.length; ++i) { if (s2.charAt(i) == "0") ++numToDelete; else break; } if (numToDelete > 0) { if (numToDelete == s2.length) --numToDelete; if (numToDelete > 0) s2 = s2.substring(numToDelete); } if (s1Sign == s2Sign && s1 == s2) return(true); } return(false); } function MultiCompare(responseText, answerText) { var startIndex; var endIndex; var partialText; responseText = responseText.toUpperCase(); answerText = answerText.toUpperCase(); startIndex = 0; do { endIndex = answerText.indexOf("\r", startIndex); if (endIndex < 0) partialText = answerText.substring(startIndex); else partialText = answerText.substring(startIndex, endIndex); if (responseText == partialText) return(true); startIndex = endIndex + 1; } while (endIndex > 0); return(false); } function FixMTF(f) { var text; var letter; var theList; var listIndex; var number; var i; for (i=0; i < f.length; ++i) { if (f.elements[i].name.indexOf("MTF:") == 0) { number = parseInt(f.elements[i].name.substring(4), 10); theList = f["MTF-" + number + "-1"]; if (theList) { listIndex = theList.selectedIndex; letter = theList.options[listIndex].text; } else letter = ""; text = StripSpaces(f["MTF-" + number + "-2"].value); if (text == "") f.elements[i].value = letter; else f.elements[i].value = letter + "," + text; } } } function AllowReset() { return(window.confirm("Do you want to clear all of your answers?")); } // -->
 
Name: 
 

Inheritance and Polymorphism



Multiple Choice
Identify the letter of the choice that best completes the statement or answers the question.
 
 
Questions 1-10 refer to the BankAccount, SavingsAccount, and CheckingAccount classes defined below:

public class BankAccount
{
      private double myBalance;

      public BankAccount()
      { myBalance = 0; }

      public BankAccount(double balance)
      { myBalance = balance; }

      public void deposit(double amount)
      { myBalance += amount; }

      public void withdraw(double amount)
      { myBalance -= amount; }

      public double getBalance()
      { return myBalance; }
}

public class SavingsAccount extends BankAccount
{
      private double myInterestRate;

      public SavingsAccount()
      { /* implementation not shown */ }

      public SavingsAccount(double balance, double rate)
      { /* implementation not shown */ }

      public void addInterest()            // Add interest to balance
      { /* implementation not shown */ }
}

public class CheckingAccount extends BankAccount
{
      private static final double FEE = 2.0;
      private static final double MIN_BALANCE = 50.0;

      public CheckingAccount(double balance)
      { /* implementation not shown */ }

      /* FEE of $2 deducted if withdrawal leaves balance less
      * than MIN_BALANCE.  Allows for negative balance. */
      public void withdraw(double amount)
      { /* implementation not shown */ }
}
 

1. 

Of the methods shown, how many different nonconstructor methods can be invoked by a SavingsAccount object?
a.
1
b.
2
c.
3
d.
4
e.
5
 

2. 

Which of the following correctly implements the default constructor of the SavingsAccount class?

I
myInterestRate = 0;
super();
  
II
super();
myInterestRate = 0;
  
III
super();

a.
II only
b.
I and II only
c.
II and III only
d.
III only
e.
I, II, and III
 

3. 

Which is a correct implementation of the constructor with parameters in the SavingsAccount class?
a.
myBalance = balance;
myInterestRate = rate;
b.
getBalance() = balance;
myInterestRate = rate;
c.
super();
myInterestRate = rate;
d.
super(balance);
myInterestRate = rate;
e.
super(balance, rate);
 

4. 

Which is a correct implementation of the CheckingAccount constructor?
I
super(balance);
  
II
super();
deposit(balance);
  
III
deposit(balance);
a.
I only
b.
II only
c.
III only
d.
II and III only
e.
I, II, and III
 

5. 

Which is correct implementation code for the withdraw method in the CheckingAccount class?
a.
super.withdraw(amount);
if (myBalance < MIN_BALANCE)
      super.withdraw(FEE);
b.
withdraw(amount);
if (myBalance < MIN_BALANCE)
      withdraw(FEE);
c.
super.withdraw(amount);
if (getBalance() < MIN_BALANCE)
      super.withdraw(FEE);
d.
withdraw(amount);
if (getBalance() < MIN_BALANCE)
      withdraw(FEE);
e.
myBalance -= amount;
if (myBalance < MIN_BALANCE)
      myBalance -= FEE;
 

6. 

Redefining the withdraw method in the CheckingAccount class is an example of
a.
method overloading.
b.
method overriding.
c.
downcasting.
d.
dynamic binding (late binding).
e.
static binding (early binding).
 
 
Use the following for Questions 7-9.

A program to test the BankAccount, SavingsAccount, and CheckingAccount classes has these declarations:

BankAccount b = new BankAccount(1400);
BankAccount s = new SavingsAccount(1000, 0.04);
BankAccount c = new CheckingAccount(500);
 

7. 

Which method call will cause an error?
a.
b.deposit(200);
b.
s.withdraw(500);
c.
c.withdraw(500);
d.
s.deposit(10000);
e.
s.addInterest();
 

8. 

In order to test polymorphism, which method must be used in this program?
a.
Either a SavingsAccount constructor or a CheckingAccount constructor
b.
addInterest
c.
deposit
d.
withdraw
e.
getBalance
 

9. 

Which of the following will not cause a ClassCastException to be thrown?
a.
((SavingsAccount) b).addInterest();
b.
((CheckingAccount) b).withdraw(200);
c.
((CheckingAccount) c).deposit(800);
d.
((CheckingAccount) s).withdraw(150);
e.
((SavingsAccount) c).addInterest();
 

10. 

A new method is added to the BankAccount class.

/* Transfer amount from this BankAccount to another BankAccount.
* Precondition:      myBalance > amount */
public void transfer(BankAccount another, double amount)
{
      withdraw(amount);
      another.deposit(amount);
}

A program has these declarations:

BankAccount b = new BankAccount(650);
SavingsAccount timeSavings = new SavingsAccount(1500, 0.03);
CheckingAccount daynasChecking = new CheckingAccount(2000);

Which of the following will transfer money from one account to another without error?

I
b.transfer(timeSavings, 50);
  
II
timeSavings.transfer(daynasChecking, 30);
  
III
daynasChecking.transfer(b, 55);

a.
I only
b.
II only
c.
III only
d.
I, II, and III
e.
None
 

11. 

Consider these class declarations:

public class Person
{
      ...
}

public class Teacher extends Person
{
      ...
}

Which is a true statement?

I
Teacher inherits the constructors of Person.
  
II
Teacher can add new methods and private instance variables.
  
III
Teacher can override existing private methods of Person.

a.
I only
b.
II only
c.
III only
d.
I and II only
e.
II and III only
 

12. 

Which statement about abstract classes and interfaces is false?
a.
An interface cannot implement any methods, whereas an abstract class can.
b.
A class can implement many interfaces but can have only one superclass.
c.
An unlimited number of unrelated classes can implement the same interface.
d.
It is not possible to construct either an abstract class object or an interface object.
e.
All of the methods in both an abstract class and an interface are public.
 

13. 

Consider the following hierarchy of classes:

cs2practice3_files/i0160000.jpg

A program is written to print data about various birds:

public class BirdStuff
{
      public static void printName(Bird b)
      { /* implementation not shown */ }

      public static void printBirdCall(Parrot p)
      { /* implementation not shown */ }

      // several more Bird methods

      public static void main(String[] args)
      {
            Bird bird1 = new Bird();
            Bird bird2 = new Parrot();
            Parrot parrot1 = new Parrot();
            Parrot parrot2 = new Parakeet();
            /* more code */
      }
}

Assuming that none of the given classes is abstract and all have default constructors, which of the following segments of /* more code */ will not cause an error?
a.
printName(parrot2);
printBirdCall((Parrot) bird2);
b.
printName((Parrot) bird1);
printBirdCall(bird2);
c.
printName(bird2);
printBirdCall(bird2);
d.
printName((Parakeet) parrot1);
printBirdCall(parrot2);
e.
printName((Owl) parrot2);
printBirdCall((Parakeet) parrot2);
 
 
Use the declarations below for Questions 14-16.

public abstract class Solid
{
      // constructor
      public Solid(String name)
      { myName = name; }

      public String getName()
      { return myName; }

      public abstract double volume();
}

public class Sphere extends Solid
{
      private double myRadius;

      // constructor
      public Sphere(String name, double radius)
      {
            super(name);
            myRadius = radius;
      }

      public double volume()
      { return (4.0/3.0) * Math.PI * myRadius * myRadius * myRadius; }
}

public class RectangularPrism extends Solid
{
      private double myLength;
      private double myWidth;
      private double myHeight;

      // constructor
      public RectangularPrism(String name, double l, double w, double h)
      {
            super(name);
            myLength = l;
            myWidth = w;
            myHeight = h;
      }

      public double volume()
      { return myLength * myWidth * myHeight; }
}
 

14. 

A program that tests these classes has the following declarations and assignments:

Solid s1, s2, s3, s4;
s1 = new Solid("blob");
s2 = new Sphere("sphere", 3.8);
s3 = new RectangularPrism("box", 2, 4, 6.5);
s4 = null;

How many of the above lines of code are incorrect?
a.
1
b.
2
c.
3
d.
4
e.
5
 

15. 

Which is false?
a.
If a program has several objects declared as type Solid, the decision about which volume mthod to call will be resolved at run time.
b.
If the Solid class were modified to provide a default implementation for the volume method, it would no longer need to be an abstract class.
c.
If the Sphere and RectangularPrism classes failed to provide an implementation for the volume method, they would need to be declared as abstract classes.
d.
The fact that there is no reasonable default implementation for the volume method in the Solid class suggests that it should be an abstract method.
e.
Since Solid is abstract and its subclasses are nonabstract, polymorphism no longer applies when these classes are used in a program.
 

16. 

Here is a program that prints the volume of a solid:

public class SolidMain
{
      /* Output volume of Solid s. */
      public static void printVolume(Solid s)
      {
            System.out.println("Volume = " + s.volume() + " cubic units");
      }

      public static void main(String[] args)
      {
            Solid sol;
            Solid sph = new Sphere("sphere", 4);
            Solid rec = new RectangularPrism("box", 3, 6, 9);
            int flipCoin = (int) (Math.random() * 2);            // 0 or 1
            if (flipCoin == 0)
                  sol = sph;
            else
                  sol = rec;
            printVolume(sol);
      }
}

Which is a true statement about this program?
a.
It will output the volume of the sphere or box, as intended.
b.
It will output the volume of the default Solid s, which is neither a sphere nor a box.
c.
A ClassCastException will be thrown.
d.
A compile-time error will occur because there is no implementation code for volume in the Solid class.
e.
A run-time error will occur because of parameter type mismatch in the method call printVolume(sol).
 

17. 

Consider the Computable interface below for performing simple calculator operations:

public interface Computable
{
      // Return this Object + y.
      Object add(Object y);

      // Return this Object - y.
      Object subtract(Object y);

      // Return this Object * y.
      Object multiply(Object y);
}

Which of the following is the least suitable class for implementing Computable?
a.
LargeInteger  (integers with 100 digits or more)
b.
Fraction (implemented with numerator and denominator of type int)
c.
IrrationalNumber (nonrepeating, nonterminating decimal)
d.
Length  (implemented with different units, such as inches, centimters, etc.)
e.
BankAccount  (implement with myBalance)
 
 
Refer to the Player interface shown below for Questions 18-21.

public interface Player
{
      /* Return an integer that represents a move in a game. */
      int getMove();

      /* Display the status of the game for this Player after
      * implementing the next move. */
      void updateDisplay();
}
 

18. 

A class HumanPlayer implements the Player interface. Another class SmartPlayer, is a subclass of HumanPlayer. Which statement is false?
a.
SmartPlayer automatically implements the Player interface.
b.
HumanPlayer must contain implementations of both the updateDisplay and getMove methods.
c.
It is not possible to declare a reference of type Player.
d.
The SmartPlayer class can override the methods updateDisplay and getMove of the HumanPlayer class.
e.
A method in a client program can have Player as a parameter type.
 

19. 

A programmer plans to write programs that simulate various games. In each case he will have several classes, each representing a different kind of competitor in the game, such as ExpertPlayer, ComputerPlayer, RecklessPlayer, CheatingPlayer, Beginner, IntermediatePlayer, and so on. It may or may not be suitable for these classes to implement the Player interface, depending on the particular game being simulated. In the games described below, which is the least suitable for having the competitor classes implement the given Player interface?
a.
High-Low Guessing Game:  The computer thinks of a number and the competitor who guesses it with the least number of guesses wins. After each guess, the computer tells whether its number is higher or lower than the guess.
b.
Chips:  Start with a pile of chips. Each player in turn removes some number of chips. The winner is the one who removes the final chip. The first player may remove any number of chips, but not all of them. Each subsequent player must remove at least one chip and at most twice the number removed by the preceding player.
c.
Chess: Played on a square board of 64 squares of alternating colors. There are just two players, called White and Black, the colors of their respective pieces. The players each have a set of pieces on the board that can move according to a set of rules. The players alternate moves, where a move consists of moving any one piece to another square. If that square is occupied by an opponent's piece, the piece is captured and removed from the board.
d.
Tic-Tac-Toe:  Two players alternate placing "X" or "O" on a 3x3 grid. The first player to get three in a row, where a row can be vertical, horizontal, or diagonal, wins.
e.
Battleships:  There are two players, each with a 10 x 10 grid hidden from his opponent. Various "ships" are placed in the grid. A move consists of calling out a grid location, trying to "hit" an opponent's ship. Players alternate moves. The first player to sink his opponent's fleet wins.
 
 
Consider these declarations for Questions 20 and 21:

public class HumanPlayer implements Player
{
      private String myName;

      // constructors not shown ...

      // code to implement getMove and updateDisplay not shown ...

      public String getName()
      { /* implementation not shown */ }
}

public class ExpertPlayer implements Player
{
      private int myRating;

      // constructors not shown ...

      public int compareTo(Object obj)
      { /* implementation not shown */ }
}
 

20. 

Which code segment in a client program will cause an error?

I
Player p1 = new HumanPlayer();
Player p2 = new ExpertPlayer();
int x1 = p1.getMove();
int x2 = p2.getMove();
  
II
int x;
Comparable c1 = new ExpertPlayer(/* correct parameter list */);
Comparable c2 = new ExpertPlayer(/* correct parameter list */);
if (c1.compareTo(c2) < 0)
      x = c1.getMove();
else
      x = c2.getMove();
  
III
int x;
HumanPlayer h1 = new HumanPlayer(/* correct parameter list */);
HumanPlayer h2 = new HumanPlayer(/* correct parameter list */);
if (h1.compareTo(h2) < 0)
      x = h1.getMove();
else
      x = h2.getMove();

a.
II only
b.
III only
c.
II and III only
d.
I, II, and III
e.
None
 

21. 

Which of the following is correct implementation code for the compareTo method in the ExpertPlayer class?

I
ExpertPlayer rhs = (ExpertPlayer) obj;
if (myRating == rhs.myRating)
      return 0;
else if (myRating < rhs.myRating)
      return -1;
else
      return 1;
  
II
ExpertPlayer rhs = (ExpertPlayer) obj;
return myRating - rhs.myRating;
  
III
ExpertPlayer rhs = (ExpertPlayer) obj;
if (getName().equals(rhs.getName()))
      return 0;
else if (getName().compareTo(rhs.getName()) < 0)
      return -1;
else
      return 1;

a.
I only
b.
II only
c.
III only
d.
I and II only
e.
I, II, and III
 

22. 

Which statement about interfaces is true?

I
An interface contains only public abstract methods and public static final fields.
  
II
If a class implements an interface and then fails to implement any methods in that interface, then the class must be declared abstrct.
  
III
While a class may implement just one interface, it may extend more than one class.
a.
I only
b.
I and II only
c.
I and III only
d.
II and III only
e.
I, II, and III
 

23. 

Which of the following classes is the least suitable candidate for implementing the Comparable interface?
a.
public class Point
{
      private double x;
      private double y;

      // various methods follow
      ...
}
b.
public class Name
{
      private String firstName;
      private String lastName;

      // various methods follow
      ...
}
c.
public class Car
{
      private int modelNumber;
      private int year;
      private double price;

      // various methods follow
      ...
}
d.
public class Student
{
      private String name;
      private double gpa;

      // various methods follow
      ...
}
e.
public class Employee
{
      private String name;
      private int hireDate;
      private double slary;

      // various methods follow
      ...
}
 

24. 

A programmer has the task of maintaining a database of students of a large university. There are two types of students, undergraduates and graduate students. About a third of the graduate students are doctoral candidates.

All of the students have the same personal information stored, like name, address, and phone number, and also student information like courses taken and grades. Each student's GPA is computed, but differently for undergraduates and graduates. The doctoral candidates have information about their dissertations and faculty advisors.

The programmer will write a Java program to handle all the student information. Which of the following is the best design, in terms of programmer efficiency and code reusability? Note: { ... } denotes class code.
a.
public interface Student {...}
public class Undergraduate implements Student {...}
public class Graduate implements Student {...}
public class DocStudent extends Graduate {...}
b.
public abstract class Student {...}
public class Undergraduate extends Student {...}
public class Graduate extends Student {...}
public class DocStudent extends Graduate {...}
c.
public class Student {...}
public class Undergraduate extends Student {...}
public class Graduate extends Student {...}
public class DocStudent extends Graduate {...}
d.
public abstract class Student {...}
public class Undergraduate extends Student {...}
public class Graduate extends Student {...}
public class DocStudent extends Student {...}
e.
public interface PersonalInformation {...}
public class Student implements PersonalInformation {...}
public class Undergraduate extends Student {...}
public abstract class Graduate extends Student {...}
public class DocStudent extends Graduate {...}
 

25. 

A certain interface provided by a Java package contains just a single method:

public interface SomeName
{
      int method1(Object o);
}

A programmer adds some functionality to this interface by adding another method to it, method2:

public Interface SomeName
{
      int method1(Object ob1);
      void method2(Object ob2);
}

As a result of this addition, which of the following is true?
a.
A ClassCastException will occur if ob1 and ob2 are not compatible.
b.
All classes that implement the original SomeName interface will need to be rewritten because they no longer implement SomeName.
c.
A class that implements the original SomeName interface will need to modify its declaration as follows:  public class ClassName implements SomeName extends method2 {...}
d.
SomeName will need to be changed to an abstract class and provide implementation code for method2, so that the original and upgraded versions of SomeName are compatible.
e.
Any new class that implements the upgraded version of SomeName will not compile.
 

26. 

Consider the Temperature class defined below:

public class Temperature implements Comparable
{
      private String myScale;
      private double myDegrees;

      // default constructor
      public Temperature()
      {/* implementation not shown */}

      // constructor
      public Temperature(String scale, double degrees)
      {/* implementation not shown */}

      public int compareTo(Object obj)
      {/* implementation not shown */}

      public String toString()
      {/* implementation not shown */}
}

public class TemperatureMain
{
      /* Find smaller of objects a and b. */
      public static Comparable min(Comparable a, Comparable b)
      {
            if (a.compareTo(b) < 0)
                  return a;
            else
                  return b;
      }

      /* Find smallest of objects a, b, and c */
      public static Comparable minThree(Comparable a, Comparable b, Comparable c)
      {
            return min(min(a, b), c);
      }

      public static void main(String[] args)
      {
            /* code to test minThree method */
      }
}

Which are correct replacements for /* code to test minThree method */?

I
Temperature t1 = new Temperature("C", 85);
Temperature t2 = new Temperature("F", 45);
Temperature t3 = new Temperature("F", 120);
System.out.println("The lowest temperature is " + minThree(t1, t2, t3));
  
II
Comparable c1 = new Temperature("C", 85);
Comparable c2 = new Temperature("F", 45);
Comparable c3 = new Temperature("F", 120);
System.out.println("The lowest temperature is " + minThree(c1, c2, c3));
  
III
Comparable c1 = new Comparable("C", 85);
Comparable c2 = new Comparable("F", 45);
Comparable c3 = new Comparable("F", 120);
System.out.println("The lowest temperature is " + minThree(c1, c2, c3));

a.
II only
b.
I and II only
c.
II and III only
d.
I and III only
e.
I, II, and III
 



 
Check Your Work     Reset Help