merged document

29
Java Foundations: Introduction to Program Design & Data Structures John Lewis, Peter J. DePasquale, Joseph Chase Test Bank: Chapter 5 Chapter 1: Introduction Multiple Choice Questions : 1)  A ________________ diagram helps us visualize the contents of and relationships among the classes of a program. a) class and object b) UML c) object-oriented d) public e) private Answer: b Explanation:  A UML diagram helps us visualize the contents and relationships among the classes of a program. The other choices do not refer to any type of diagram. 2)  Which of the following object-oriented principles refers to the fact that an object should have its data guarded from inappropriate access? a) encapsulation b) inheritance c) polymorphism d) instance variables e) methods Answer:  a Explanation:  Encapsulation is the object-oriented principle that specifies that an objects data should be guarded from inappropriate access.  Therefore choice a is correct.  Inheritance and polymorphism are features of object-oriented programming that allow for class flexibility and re-use.  Instance variables and methods play important roles in object- oriented programming, but are not fundamental principles. 3)  When applied to instance variables, the ________________ visibility modifier enforces encapsulation. a) static b) final c) public d) private e) none of the above Answer:  d Explanation:  The private visibility modifier guards against inappropriate data access, and therefore promotes encapsulation.  Choices a and b are not visibility modifiers, and choice c is a visibility modifier that allows public access to an objects data, which violates the principle of encapsulation. 4)  Which of the following types of methods do not have any return type (not even a void return type)? a) methods declared as static 1 Addison-Wesley © 2007

Upload: andrea-james

Post on 01-Dec-2015

1.994 views

Category:

Documents


0 download

DESCRIPTION

Merged Document

TRANSCRIPT

Java Foundations: Introduction to Program Design & Data StructuresJohn Lewis, Peter J. DePasquale, Joseph Chase

Test Bank: Chapter 5

Chapter 1: Introduction

Multiple Choice Questions:

1)  A ________________ diagram helps us visualize the contents of and relationships among the classes of a program.

a) class and objectb) UMLc) object­orientedd) publice) private

Answer: bExplanation:  A UML diagram helps us visualize the contents and relationships among the classes of a program. 

The other choices do not refer to any type of diagram.

2)  Which of the following object­oriented principles refers to the fact that an object should have its data guarded from inappropriate access?

a) encapsulationb) inheritancec) polymorphismd) instance variablese) methods

Answer:  aExplanation:  Encapsulation is the object­oriented principle that specifies that an objects data should be guarded 

from inappropriate access.  Therefore choice a is correct.  Inheritance and polymorphism are features of object­oriented programming that allow for class flexibility and re­use.  Instance variables and methods play important roles in object­oriented programming, but are not fundamental principles.

3)  When applied to instance variables, the ________________ visibility modifier enforces encapsulation.

a) staticb) finalc) publicd) privatee) none of the above

Answer:  dExplanation:  The private visibility modifier guards against inappropriate data access, and therefore promotes 

encapsulation.  Choices a and b are not visibility modifiers, and choice c is a visibility modifier that allows public access to an objects data, which violates the principle of encapsulation.

4)  Which of the following types of methods do not have any return type (not even a void return type)?

a) methods declared as static

1Addison­Wesley © 2007

Java Foundations: Introduction to Program Design & Data StructuresJohn Lewis, Peter J. DePasquale, Joseph Chase

Test Bank: Chapter 5

b) methods declared as publicc) methods declared as privated) constructorse) all of the above have return types

Answer: dExplanation:  Constructors are the only methods that do not have any return type.  They do not even have a void 

return type.  All of the other methods must specify a return type or be declared as void.

5)  Which of the following method headers is most likely a header for a mutator method?

a) public int getAge()b) public double computeSalary()c) public Person()d) public void setAge(int newAge)e) none of these are headers for a mutator method

Answer: dExplanation:  Mutators are methods that change the value of an instance variable, and are often referred to as 

“setters.”  Therefore, choice d is the correct answer.  Choice a is an example of a header for a accessor method, often referred to as a “getter.”  Choice c is a constructor, and choice b is a class method.

6)  A _______________ variable is shared among all instances of a class.

a) staticb) finalc) publicd) privatee) none of the above

Answer: aExplanation:  A static variable is shared among all instances of a class.  A final variable is a constant, a public 

variable is one that is accessible from outside the object and a private variable is one that cannot be accessed outside of the object.  

7)  __________________ parameters are the values that are used when calling a method. 

a) formalb) actualc) usefuld) informale) none of the above

Answer: bExplanation:  Actual parameters are sent in when calling a method.  Formal parameters are used when defining a 

method.

8)  The ________________ reference always refers to the currently executing object.

2Addison­Wesley © 2007

Java Foundations: Introduction to Program Design & Data StructuresJohn Lewis, Peter J. DePasquale, Joseph Chase

Test Bank: Chapter 5

a) nullb) staticc) finald) actuale) this

Answer: eExplanation:  The this reference always refers to the currently executing object.  A null reference is a reference 

that is not pointing to any object.  The other three choices are not special references in Java.

9)  A method that has multiple definitions is an __________________ method.

a) overloadedb) overriddenc) overlookedd) overclockede) none of the above

Answer: aExplanation:  A method that has multiple definitions is an overloaded method.  The versions of an overloaded 

method are distinguished by the number, type and order of their parameters.  Overridden methods are methods that have been redefined later in an inheritance hierarchy.  They will be studied in more detail later.  Choice c and d are not types of methods in Java.

10)  A(n) ________________ is a step­by­step process for solving a problem.

a) UML diagramb) aggregate objectc) classd) algorithme) none of the above

Answer: dExplanation:  An algorithm is a step­by­step solution for solving a problem.  A UML diagram is a way of visually 

representing how classes and objects interact.  An aggregate object is an object that is composed, in part, of other objects.  A class can be thought of as a blueprint for a set of objects.

11)  All methods (with the exception of constructors) must specify a return type.  What is the return type for a method that does not return any values?

a) intb) publicc) doubled) voide) none of the above

Answer: d

3Addison­Wesley © 2007

Java Foundations: Introduction to Program Design & Data StructuresJohn Lewis, Peter J. DePasquale, Joseph Chase

Test Bank: Chapter 5

Explanation:  Methods that do not need to return any data should have void specified as the return type.  A method cannot have public specified as its return type, so choice b is incorrect.  Choice a and choice c specify a return type, and therefore they must return data of that type.

12)  Methods that can be called directly through the class name and do not need to have an object instantiated are called _________________.

a) finalb) publicc) staticd) privatee) none of the above

Answer: cExplanation: Methods that can be called directly through the class name must be declared as static.  Choice b 

and choice d are visibility modifiers for a method.  Methods declared as final cannot be overridden.

13)  A(n) ___________________ object is one that is made up, at least in part, of other objects.

a) staticb) aggregatec) encapsulatedd) privatee) public

Answer: bExplanation: An aggregate object is one that is made up of other objects.  Choice a, d and e do not refer to types of 

objects.  Encapsulated objects may be made up of primitive types or object types.

14)  If a service is so complex that it cannot be reasonably be implemented using one method, it is often helpful to decompose it to make use of ________________ support methods. 

a) staticb) aggregatec) privated) publice) final

Answer: cExplanation: Private support methods are useful when a service is too complex to be defined in a single method. 

Therefore choice d is correct.

15)  The versions of an overloaded method are distinguished by ___________________________.

a) the number, type and order of their parametersb) their identifiersc) their classesd) the number and type of their parameters

4Addison­Wesley © 2007

Java Foundations: Introduction to Program Design & Data StructuresJohn Lewis, Peter J. DePasquale, Joseph Chase

Test Bank: Chapter 5

e) the number of their parameters

Answer: aExplanation:  Overloaded methods are two methods in the same class that have the same identifier, but a different 

number, type or order of parameters.  Therefore, choice a is correct and the rest are incorrect.

5Addison­Wesley © 2007

Java Foundations: Introduction to Program Design & Data StructuresJohn Lewis, Peter J. DePasquale, Joseph Chase

Test Bank: Chapter 5

True/False Questions:

1)   A variable can always be referenced anywhere in a program.Answer:  FalseExplanation:  The scope of a variable determines where it can be referenced.  It depends on where the variable is 

declared.

2)   An object can be thought of as a blueprint for a set of classes.Answer: FalseExplanation: A class can be thought of as a blueprint for a set of objects; not the other way around.

3)   A return statement is not required at the end of every method.Answer:  TrueExplanation:  A return statement is not required at the end of a constructor or any method declared with the return 

type void.

4)   When an object is passed to a method, the actual and formal parameters become aliases.Answer: TrueExplanation:  Actual parameters are the datum that are sent into the method.  The formal parameters are used in the 

method definition.  When objects are sent to a method, both of these values are references, and they become aliases of one another.

5)  There are times when it is appropriate to return data from a method of a type that is inconsistent with the return type specified in the method header.

Answer:  FalseExplanation:  The value returned from a method must be consistent with the return type specified in the method 

header.

6)   A main method can only access static or local variables.Answer:  TrueExplanation:  A main method cannot access non­static and non­local variables because it is a static 

method.  In particular, it cannot access any variables declared at the class level.

7)   In a class that has variables called height and width, methods called getHeight() and getWidth() are examples of accessor methods.

Answer:  TrueExplanation:  Accessor methods get the value of instance variables.  In contrast, mutators set the values.

8)   A programmer is required to define a constructor for every class.Answer:  FalseExplanation:  Every class automatically has a default constructor that doesn't take any parameters.

9)   Variables that are declared as static are shared among all instances of a class.Answer:  TrueExplanation:  Static variables are sometimes called class variables because they are shared among all instances of a 

class.

10)  Aggregation is sometimes described as a has­a relationship.

6Addison­Wesley © 2007

Java Foundations: Introduction to Program Design & Data StructuresJohn Lewis, Peter J. DePasquale, Joseph Chase

Test Bank: Chapter 5

Answer:  TrueExplanation: Aggregate objects are made up of other objects.  Therefore the relationship between an object that is 

an aggregate of other objects is often described as a has­a relationship.

7Addison­Wesley © 2007

Java Foundations: Introduction to Program Design & Data StructuresJohn Lewis, Peter J. DePasquale, Joseph Chase

Test Bank: Chapter 5

Short Answer Questions:

1)  What is the difference between an object and a class?

Answer:  A class can be thought of as the blueprint for an object.  In other words, the object is the embodiment of a class.

2)  Explain the difference between actual parameters and formal parameters.

Answer:  Formal parameters are used in the definition of a method, while actual parameters are the values that are used in the method call.

3)  What is encapsulation?  How can it be enforced in Java?

Answer:  Encapsulation is the principle that objects should be self­governing.  In other words, an object's internal data should be protected from outside access.  Encapsulation can be enforced in Java by making instance variables private.

4)  Write a method called maxOfThree that accepts three integer parameters and returns the largest of the three.

Answer:

public int maxOfThree(int firstInt, int secondInt, int thirdInt)  {if(firstInt >= secondInt && firstInt >= thirdInt)

return firstInt;else if(secondInt >= firstInt && secondInt >= thirdInt)

return secondInt;else

return thirdInt;}

5)  Write a method called randomInRange that takes in two numbers representing a range.  Print an error message and return zero if the second parameter is less than the first.  Otherwise, the method should return a randomly generated integer in that range (inclusive).  You may assume that the class has a static Random object called generator already declared and instantiated.

Answer:

public int randomInRange(int a, int b)  {if(b < a)  {

System.out.println(“Error, invalid range!”);return 0;

}

return generator.nextInt(b – a + 1) + a;}

6)  Write a method called isPalindrome that accepts a String as a parameter and returns true if the String is a palindrome, and false otherwise.  You may assume that the entered String consists entirely of lowercase letters (meaning it 

8Addison­Wesley © 2007

Java Foundations: Introduction to Program Design & Data StructuresJohn Lewis, Peter J. DePasquale, Joseph Chase

Test Bank: Chapter 5

contains no numbers, spaces, punctuation, etc).  Hint:  write code that creates a new string that is the original string reversed, and then check to see if the two strings are equal.

Answer:

public boolean isPalindrome(String s)  {String reverseS = new String(“”);

for(int i = s.length()­1; i >= 0; i­­)reverseS += s.charAt(i);

return reverseS.equals(s);}

7)  Write a method called countSpaces that takes in a String as a parameter and returns an integer that represents the number of space characters (' ') contained in the string, false otherwise..

Answer:

public int countSpaces(String s)  {int count = 0;for(int i = 0; i < s.length(); i++)

if(s.charAt(i) == ' ')count++;

return count;}

8)  Write a method called containsPair that takes in three integer parameters and returns true if any two of the input parameters are the same.

Answer:

public boolean containsPair(int a, int b, int c)  {return (a == b || a == c || b == c);

}

9)  Write a method called threeOfAKind that takes in three integer parameters and returns true if all three of them are the same, false otherwise.

Answer:

public boolean threeOfAKind(int a, int b, int c)  {return (a == b && b == c);

}

10)  Write a method called randomAverage that generates 100 random integers in the range 1 to 100 (inclusive) and returns their average.  You may assume that the class has a static Random object called generator already declared and instantiated.

9Addison­Wesley © 2007

Java Foundations: Introduction to Program Design & Data StructuresJohn Lewis, Peter J. DePasquale, Joseph Chase

Test Bank: Chapter 5

Answer:

public double randomAverage()  {int sum = 0;for(int i = 0; i < 100; i++)

sum += generator.nextInt(100) + 1;

return (double) sum/100.0;}

11)  Explain why a static method cannot refer to an instance variable.

Answer:  Static methods may be called without instantiating an object.  Therefore, an instance variable may not have an assigned value when a static method is called, so a static method cannot reference it.

12)  Write a method that prints your name, age, and major.  The method should accept no parameters and return no value.

Answer:

public void myInfo()  {System.out.println(“Name:\tJohn Smith”);System.out.println(“Age:\t30”);System.out.println(“Major:\tBasket Weaving”);

}

13)  Explain why method overloading is useful.

Answer:  Method overloading is useful because it allows multiple methods to have the same name as long as they have different parameter types.  This allows for more flexibility in choosing identifiers for methods, since the alternative would require the programmer to have different method identifiers for every method that took in a different type of parameter.

14)  Consider the following method.

public void changeValues(int i, Card c)  {i = 15;c.setSuit(“Clubs”);

}

Now consider the following snippet of code that calls the method defined above.

int num = 12;Card fiveOfSpades = new Card(5, “Spades”);

System.out.println(“Before method call:”);System.out.println(num);System.out.println(fiveOfSpades.getSuit());

10Addison­Wesley © 2007

Java Foundations: Introduction to Program Design & Data StructuresJohn Lewis, Peter J. DePasquale, Joseph Chase

Test Bank: Chapter 5

changeValues(num, fiveOfSpades);

System.out.println(“After method call:”);System.out.println(num);System.out.println(fiveOfSpades);

What is the output of this code?

Answer:

Before method call:12SpadesAfter method call:12Clubs

15)  Write a method called square that takes in an integer value and returns the integer squared.  Your method should use the Math.pow() method.

Answer:

public int square(int a)  {return Math.pow(a, 2);

}

11Addison­Wesley © 2007

Java Foundations: Introduction to Program Design & Data StructuresJohn Lewis, Peter J. DePasquale, Joseph Chase

Test Bank: Chapter 8

Chapter 1: Introduction

Multiple Choice Questions:

1)  The process of inheritance should establish a(n) ___________________ relationship.

a) is­ab) has­ac) staticd) not­ae) none of the above

Answer: aExplanation:  Inheritance should establish an is­a relationship.  Therefore any objects that are of a type lower in the 

inheritance hierarchy are also of a type higher in the inheritance hierarchy.

2)  The original class that is used to derive a new class using inheritance is called ____________________ .

a) a superclassb) a parent classc) a base classd) all of the abovee) neither a, b, nor c

Answer:  dExplanation:  The original class can be called a superclass, a parent class and/or a base class.  

3)  The derived class created using inheritace is called ______________________ .

a) a child classb) a superclassc) a parent classd) all of the abovee) neither a, b, nor c

Answer: aExplanation:  A derived class is called a child class.  The super class and the parent class refers to the original class 

used to derive the child class.

4)  In order for derived classed to have access to encapsulated data members and methods of superclasses, the data members and methods should be declared using the ____________________ modifier.

a) privateb) publicc) protectedd) finale) static

1Addison­Wesley © 2007

Java Foundations: Introduction to Program Design & Data StructuresJohn Lewis, Peter J. DePasquale, Joseph Chase

Test Bank: Chapter 8

Answer:  cExplanation:  Data members and methods declared using the protected modifier can be accessed by subclasses in 

an inheritance hierarchy, but are still encapsulated from classes and methods outside of the hierarchy.

5)  The special reference _________________ is used to refer to the parent class in a child class.

a) thisb) superc) nulld) parente) none of the above

Answer: bExplanation:  The super reference refers to the parent class in a derived class.

6)  When a variable is declared in a subclass has the same name as a variable declared in a superclass, it is called a _______________ variable.

a) finalb) shadowc) staticd) deade) this is not allowed in Java

Answer: bExplanation:  A shadow variable is a variable in a subclass with the same name as a variable in the superclass.

7)  A _______________________ class represents a generic concept in a class hierarchy.

a) superb) abstractc) interfaced) shadowe) generic

Answer: bExplanation:  An abstract class represents a generic entity that is not completely defined.  An abstract class cannot 

be instantiated.  It contains one or more abstract methods, which are methods that should be overridden by subclasses.

8)  A class declared as final _________________________________ .

a) cannot be changed.b) cannot have subclasses.c) cannot have superclasses.d) has several abstract methods.e) cannot be used in a program.

2Addison­Wesley © 2007

Java Foundations: Introduction to Program Design & Data StructuresJohn Lewis, Peter J. DePasquale, Joseph Chase

Test Bank: Chapter 8

Answer:  b  Explanation:  The final modifier restricts inheritance.  In particular, a class declared as final cannot have 

subclasses.

9)  Which of the following key words indicates a new class is being derived from an existing class?

a) superb) finalc) extendsd) inheritse) expands

Answer:  cExplanation:  The key word extends indicates that a new class is being derived from an existing class.

10)  To invoke a parents constructor in a subclass, we use the ______________ method.

a) abstractb) constructc) parentd) supere) extends

Answer: dExplanation:  The super method is used to invoke a parents constructor from a subclass.

11)  If a subclasses constructor does not make an explicit call to a superclass's constructor, ______________________ .

a) a run­time error will result.b) a compile­time error will result.c) the constructor will be called anyway.d) the class will be implicitly declared as abstract.e) none of the above

Answer:  cExplanation:  The child's constructor will implicitly call the superclass's constructor if it is not done explicitly.  This 

will ensure that the class is properly initialized.

12)  All Java classes are subclasses of the ___________________ class.

a) Stringb) java.langc) Javad) Classe) Object

Answer: eExplanation:  All classes are subclasses of Java's Object class, whether explicitly specified or not.

3Addison­Wesley © 2007

Java Foundations: Introduction to Program Design & Data StructuresJohn Lewis, Peter J. DePasquale, Joseph Chase

Test Bank: Chapter 8

13)  When designing a class hierarchy, it is important that common features be ________________________ .  

a) higher in the class hierarchy.b) lower in the class hierarchy.c) near the middle of the class hierarchy.d) in abstract classes.e) in the Object class.

Answer: aExplanation:  Common features should be included closer to the top of the class hierarchy.  Doing this makes them 

available to more classes lower in the hierarchy.

14)  Which of the following methods are included in every class created in Java by inheritance?

a) nextb) toStringc) compareTod) charAte) none of the above

Answer: bExplanation:  The toString method is defined in the Object class, and is therefore included in every Java class 

via inheritance.

15)  Of the classes below, the one that is most likely to be declared abstract is  _________________. 

a) Batb) Squirrelc) Animald) Iguanae) Parrot

Answer: cExplanation:  The Animal class is most likely to be abstract since it is the most generic.

4Addison­Wesley © 2007

Java Foundations: Introduction to Program Design & Data StructuresJohn Lewis, Peter J. DePasquale, Joseph Chase

Test Bank: Chapter 8

True/False Questions:

1)   Methods and variables declared as private in a parent class cannot be accessed in a child class.Answer:  TrueExplanation:  In order for a child class to have access to the private data and methods of a parent class, they should 

be declared using the protected modifier, which still enforces encapsulation, but allows for flexibility in an inheritance hierarchy.

2)   Once a method is overridden in a subclass, the original version can never be referenced from within the subclass.Answer:  FalseExplanation:  The original version of the method can be accessed using the super reference.

3)   Java supports multiple inheritance.Answer:  FalseExplanation:  Java does not support true multiple inheritance, but it is possible to get some of the features of 

multiple inheritance using interfaces.

4)   In Java subclass can only extend one parent class.Answer:  TrueExplanation:  Allowing a subclass to extend multiple parent classes leads to multiple inheritance, which is not 

supported in Java.

5)   A child class is allowed to define a method with the same name and parameter list as a method in the parent class.Answer:  TrueExplanation:  A subclass is allowed to override methods that are in the parent class.

6)   A child class is allowed to declare a variable with the same name as one that is contained in the parent class.Answer:  TrueExplanation:  This is known as variable shadowing and can lead to confusion.  It is, however, permitted in Java.

7)   An abstract class must contain abstract methods.Answer:  FalseExplanation:  A class declared as abstract may or may not contain abstract methods.

8)   It makes sense to declare most abstract methods as final.Answer:  TrueExplanation:  Since an abstract class cannot be instantiated, it makes no sense to declare it as final.  It is usually 

expected that an abstract class will be extended.

9)   It is possible to derive a class from an abstract class without overriding all of the parents abstract methods.Answer:  TrueExplanation:  The child class must also be declared as abstract in this case.

10)   Inheritance should not be considered in the software design process.Answer:  FalseExplanation: Inheritance should be carefully considered in the software design process.  Software systems designed 

carefully using inheritance can be more flexible than software designed without considering inheritance.

5Addison­Wesley © 2007

Java Foundations: Introduction to Program Design & Data StructuresJohn Lewis, Peter J. DePasquale, Joseph Chase

Test Bank: Chapter 8

Short Answer Questions:

1)  Explain why inheritance is useful.

Answer:  Inheritance is useful because it allows for code­reuse.  This means that if we have multiple software entities that have common features, the code for the common features can be written once in a superclass.  The classes that include these features can then be written via inheritance, and this common code does not have to be rewritten.

2)  Compare and contrast the private visibility modifier to the protected visibility modifier.  Why is the protected visibility modifier a better choice in an inheritance hierarchy?

Answer:  The private modifier and the protected modifier both enforce the encapsulation of instance variables and methods in a class.  This means that unrelated classes are not able to directly access the variables and the methods.  The protected modifier, however, does allow for the instance variables and the methods to be accessed by subclasses of the original class.  This makes the protected modifier a better choice for use in an inheritance hierarchy, because it is often useful for subclasses to have access to a superclass's instance variables and methods. 

3)  Suppose we create a subclass from a class that has a method called someMethod.  If we override someMethod in the subclass, is it possible to access the superclass's version of someMethod?  If so, how?

Answer:  Yes, it is possible to access the original version of the method.  To do so, we qualify the call to the method with the super reference.  In other words, to access the original version of the method we call super.someMethod().

4)  Can a class be a parent of more than one subclass?  Can a class be a child of more than one parent?  Explain.

Answer:  A class can be the parent of more than one subclass in an inheritance hierarchy. Classes that have the same parent class are often called siblings.  In Java, a class cannot be the child of more than one parent since Java does not support multiple inheritance.

5)  Explain the relevance of the Object class to the Java programming language.

Answer:  Every class in Java is a subclass of the Object class.  This occurs whether a class definition explicitly extends the Object class or not.  Therefore, every class in Java has a common set of methods that are defined in the Object class.  These include the toString method and the equals method. 

6)  What is an abstract class, and why might it be useful in an inheritance hierarchy?

Answer:  An abstract class is a class represents a partially defined concept in an inheritance hierarchy.  Abstract methods cannot be instantiated, but they can be extended.  They are often useful because several classes may include common functionality but may lack a fully defined parent concept.  Abstract classes allow a programmer to implement the partially defined parent concept as an abstract class which will include the common functionality of the child classes.  An example of an abstract concept in an inheritance hierarchy might be a Vehicle.  Subclasses like Car, Boat and Airplane are more fully defined, but they share common states and behaviors.

7)  Explain how a subclass can can access its parent classes private instance variables and methods.

Answer:  A subclass can access private instance variables and methods of its parent class, but only indirectly. There must be public methods that access the private data and methods directly.  These public methods can then be called by 

6Addison­Wesley © 2007

Java Foundations: Introduction to Program Design & Data StructuresJohn Lewis, Peter J. DePasquale, Joseph Chase

Test Bank: Chapter 8

the subclass, which gives indirect access to the private variables and methods of the parent class.

8)  A programmer tries to create a subclass of String called MyString.  When the programmer compiles her new class, the compiler produces the following message:

MyString.java:1: cannot inherit from final java.lang.Stringpublic class MyString extends String {

                              ^1 error

Explain the cause of this error.

Answer:  The String class has been declared with the final modifier, which restricts any other classes from extending it.

9)  Draw a hierarchy of Animals.  The hierarchy should include the following entities: Animal, Reptile, Mammal, Bear, Human, Iguana, and Dolphin. 

Answer:

 Animal/   \

     Reptile        Mammal                 /            /   |    \               Iguana       Bear Human  Dolphin

10)  Consider an software system that will implement the following classes:  Student, Professor, StaffMember, ContractWorker.   List some common attributes of these classes.  What would be a good abstract class from which these classes may be extended via inheritance?

Answer:  Some common attributes would be socialSecurityNumber, age, and address.  A good abstract class from which these classes could be extended is Person.

11)  Explain what it means for a child class to override a parent class.  Why might this be useful?

Answer:  A child class overrides a method that is inherited from a parent class by redefining it in the subclass.  This is useful because a subclass may have a slightly different behavior than the superclass, but the behavior still has the same name.  Overriding methods allows for this flexibility.

12)  Draw a hierarchy of people at a University.

Answer:

                         UniversityPerson/        |        \

                      Faculty       Staff       Student                     /     |                    /      \           Professors   Instructors      Graduate       Undergraduate

7Addison­Wesley © 2007

Java Foundations: Introduction to Program Design & Data StructuresJohn Lewis, Peter J. DePasquale, Joseph Chase

Test Bank: Chapter 8

13)  Describe the behavior of the toString method and the equals method of the Object class.

Answer:  The toString method returns a String representation of an object.  The equals method returns true if the object is an alias of the object sent in as a parameter.

14)  What does it mean for a class to be declared as final?  What does it mean for a method to be declared as final?

Answer:  A method declared as final cannot be overridden by any subclass.  A class declared as final can not be extended via inheritance.

15)  What is a shadow variable?

Answer:  A shadow variable is a variable that is declared in a subclass that has the same name as a variable declared in the class's parent class.

8Addison­Wesley © 2007

Java Foundations: Introduction to Program Design & Data StructuresJohn Lewis, Peter J. DePasquale, Joseph Chase

Test Bank: Chapter 9

Chapter 1: Introduction

Multiple Choice Questions:

1)  A polymorphic reference is one that can refer to _______________ type(s) of object(s).

a) exactly oneb) zeroc) multipled) abstracte) static

Answer:  cExplanation:  A polymorphic reference can point to multiple types of objects at different points in time.

2)  The commitment to execute certain code to carry out a method invocation is referred to as _________________.

a) executionb) bindingc) polymorphismd) inheritancee) none of the above

Answer: bExplanation:  Binding refers to the commitment to execute certain code to carry out a method invocation.

3)  In Java, polymorphic method binding occurs ____________________ .

a) at run timeb) at compile timec) neverd) when a programmer writes the codee) during the testing phase of software development

Answer: aExplanation: polymorphic method binding occurs at run­time.

4)  Late binding is _______________  than _______________ .

a) more efficient, compile­time bindingb) less efficient, compile­time bindingc) more efficient, run­time bindingd) less efficient, run­time bindinge) 

Answer: bExplanation:  Late binding is less efficient than compile­time binding due to the overhead associated with 

1Addison­Wesley © 2007

Java Foundations: Introduction to Program Design & Data StructuresJohn Lewis, Peter J. DePasquale, Joseph Chase

Test Bank: Chapter 9

determining the code that should be executed at run time.

5)  Suppose that Horse is a subclass of Animal, and neither class is abstract.  Which of the following is an invalid declaration and initialization?

a) Horse h = new Horse(); b) Horse h = new Animal();c) Animal a = new Animal();d) Animal a = new Horse();e)  all of the above are valid

Answer:  bExplanation:  Since Horse is a subclass of Animal, choice b would require an explicit class.

6)  In Java, a(n) ___________________ is a collection of constants and abstract methods.

a) polymorphic referenceb) abstract classc) implementationd) interfacee) iterator

Answer:  dExplanation:  An interface is a collection of constants and abstract methods.

7)  In Java, polymorphic references can be created through the use of  __________________ and ________________.

a) inheritance, interfacesb) inheritance, abstract classesc) interfaces, abstract classesd) interfaces, iteratorse) none of the above

Answer:  aExplanation:  In Java, polymorphic references can be created through the use of inheritance and interfaces.

8)  Let Dog be a subclass of Animal, and suppose Animal has a method called speak() that is overridden in the Dog class. Consider the following code.

Animal spot = new Dog();spot.speak();

Which of the following is true?

a) This code will result in a compile­time error.b) This code will result in a run­time error.c) The speak method defined in the Animal class will be called.d) The speak method defined in the Dog class will be called.

2Addison­Wesley © 2007

Java Foundations: Introduction to Program Design & Data StructuresJohn Lewis, Peter J. DePasquale, Joseph Chase

Test Bank: Chapter 9

e) The speak method will not be called at all.

Answer:  dExplanation:  The speak method defined in the Dog class will be called in this case.  At run­time, the Java virtual 

machine determines that spot is pointing to an object of type Dog and binds the method to the methods defined in the Dog class.

9)  The Comparable interface contains which of the following methods?

a) isGreaterThanb) isLessThanc) equalsd) compareToe) all of the above

Answer: dExplanation:  The Comparable interface contains exactly one method ­­ compareTo.

10)  Let Object a be larger than Object b.  What will the following method call return?

a.compareTo(b)

a) it will return 0b) it will return a number greater than 0c) it will return a number less than 0d) it will return truee) it will return false

Answer:  bExplanation:  The compareTo method returns an integer.  If Object a is bigger than Object b, it will return 

a number greater than 0.If Object a is less than Object b, it will return a number less than 0.  If they are equal it return 0.

11)  Which of the following methods are included with any object that implements the Iterator interface?

a) nextb) hasNextc) toStringd) all of the abovee) a and b

Answer: dExplanation:  The Iterator interface specifies that all objects that implement it must have the hasNext and next 

methods.  Since all objects in Java are a subclass of the Object class, it will also include the toString method.

12)  In order to create a class that implements an interface, the __________________ keyword is used.

3Addison­Wesley © 2007

Java Foundations: Introduction to Program Design & Data StructuresJohn Lewis, Peter J. DePasquale, Joseph Chase

Test Bank: Chapter 9

a) extendsb) interfacesc) implementsd) finalizese) abstracts

Answer:  cExplanation:  A class that implements an interface uses the implements keyword to declare the class. 

13)  Consider the following line of code.

Comparable s = new String();

Which of the following statements is true about this line?

a) It will result in a compile­time error.b) It will result in a run­time error.c) It will create a String object pointed to by a Comparable reference.d) Although it is perfectly valid Java, it should be avoided due to confusion. e) none of the above are true

Answer:  cExplanation:  This is a valid Java statement and will result in no errors, since the String class implements the 

Comparable interface.

14)  Suppose Animal is an interface that specifies a single method – speak.  Now suppose the Dog class implements the Animal interface.  In addition to the speak method, the Dog class also has a method called wagTail.  Now consider the following code.

Animal a = new Dog();a.wagTail();

Which of the following is true about this code?

a) It will result in a compile­time error.b) It will result in a run­time error.c) It will call the speak method defined in the Animal interface.d) It will call the wagTail method defined in the Dog class.e) none of the above are true.

Answer:  aExplanation:  This code will result in a compile­time error since the Animal interface does not specify a 

wagTail method.  This compile­time error can be avoided by explicitly casting a as a Dog when calling the wagTail method.

15)  Which GUI concepts use polymorphism to establish their relationship?

a) a listener and its associated component

4Addison­Wesley © 2007

Java Foundations: Introduction to Program Design & Data StructuresJohn Lewis, Peter J. DePasquale, Joseph Chase

Test Bank: Chapter 9

b) a radio button and its default selectionc) a button and its labeld) a slider and its tick markse) none of the above

Answer: aExplanation:  Polymorphism is used to establish the relationship between a listener and its associated component.

5Addison­Wesley © 2007

Java Foundations: Introduction to Program Design & Data StructuresJohn Lewis, Peter J. DePasquale, Joseph Chase

Test Bank: Chapter 9

True/False Questions:

1)   Consider a reference declared in the following manner.

Animal a;

This reference may only point to an object that created by instantiating the Animal class.

Answer: FalseExplanation:  This reference may point to an object of any type that is compatible with Animal.  In particular, it 

may point to any object that is an instance of a class that is a subclass of Animal.

2)  Let Animal be an interface.  Then it is possible to create an object by instantiating the Animal interface.Answer:  FalseExplanation:  An interface cannot be instantiated.

3)   The compareTo method of the Comparable interface returns a boolean value.Answer: FalseExplanation:  The compareTo method returns an integer.

4)  The next method of the Iterator interface returns a reference to the next element in a collection and removes it.Answer:  FalseExplanation:  The next method only returns a reference to the next element in a collection; it does not remove it.

5)  A parameter to a method can be polymorphic.Answer:  TrueExplanation:  A method can accept a polymorphic reference; this gives the method more flexibility than it would 

otherwise have.

6)  An interface cannot declare any instance variables. Answer:  TrueExplanation:  An interface may only declare constants.

7)   Establishing the relationship between a listener and the component it listens to is accomplished using polymorphism.Answer:Explanation:

8)   If a class implements an interface, it cannot extend another class.Answer: FalseExplanation:  A class may implement an interface and extend another class.

9)   A single class may implement multiple interfaces.Answer:  TrueExplanation:  A class may implement multiple interfaces, which gives Java many of the good features of multiple 

inheritance.

10)   An interface name may be used as a reference type.Answer:  True

6Addison­Wesley © 2007

Java Foundations: Introduction to Program Design & Data StructuresJohn Lewis, Peter J. DePasquale, Joseph Chase

Test Bank: Chapter 9

Explanation:  An interface name may be used a reference type in the same way that a class name may be used as a reference type.  Like an abstract class, an interface cannot be instantiated, however. 

7Addison­Wesley © 2007

Java Foundations: Introduction to Program Design & Data StructuresJohn Lewis, Peter J. DePasquale, Joseph Chase

Test Bank: Chapter 9

Short Answer Questions:

1)  What is polymorphism?

Answer:  A polymorphic reference is a single type of reference that can point to different types of objects at different times.  Polymorphism refers to the fact that the method calls on polymorphic references are selected by the object type, not the reference type.  This is often referred to as late binding.

2)  How does inheritance relate to polymorphism in Java?

Answer:  Inheritance is the process by which polymorphic references are created.  A reference to a type higher in an inheritance hierarchy can always point to an object of a type lower in an inheritance hierarchy due to the is­a relationship.

3)  Consider a class hierarchy that includes a class called Vehicle, with subclasses called Car and Airplane.  The Vehicle class has a method called getMaxSpeed, which is overridden in the Car class.  The getMaxSpeed of the Vehicle class returns  760 mph, while the getMaxSpeed method of the Car class is overridden to return 150 mph. What is the output of the following snippet of code?  Explain your answer.

Vehicle v = new Car();System.out.println(v.getMaxSpeed() + “ mph”);

Answer:  The output of this code will be “150 mph”.  Even though the reference is to the Vehicle class, the getMaxSpeed method is bound to the definition in the Car class, since the object is a car.  This is due to the polymorphic nature of the reference.

4)  Consider the following inheritance hierarchy that is used in a video game.

                        Character                    /              \              Friend                Villain          /          \           /            \       WiseMan    ShopKeeper    Dragon         Skeleton                                  |                |                              FlyingDragon      EliteSkeleton                                                                 

Which of the following declarations and initializations will not cause a compiler error?

Character c = new FlyingDragon();FlyingDragon f = new Character();Dragon d = new Villain();Villain v = new Skeleton();Dragon d = new ShopKeeper();

Answer:  The following are valid for this inheritance hierarchy because of the is­a relationship.

Character c = new FlyingDragon();

8Addison­Wesley © 2007

Java Foundations: Introduction to Program Design & Data StructuresJohn Lewis, Peter J. DePasquale, Joseph Chase

Test Bank: Chapter 9

Villain v = new Skeleton();

5)  What is an interface?

Answer:  An interface is a collection of abstract methods and constants.

6)  Are there any differences between extending a class and implementing an interface?

Answer:  Yes.  First, extending a class uses the extends keyword, while implementing an interface uses the implements keyword.  More importantly, a class can implement multiple interfaces, while it can only extend a single class.

7)  Describe the compareTo method the circumstances under which it returns different values.

Answer:  The compareTo method is specified by the Comparable interface.  It places an ordering on objects. Consider the following call to compareTo:

int result = obj1.compareTo(obj2);

In this case result will be positive if obj1 is larger than obj2 in the sense of the ordering.  It will be 0 if obj1 and obj2 are the same, and it will be negative if obj2 is larger than obj1.

8)  How do interfaces relate to multiple inheritance?

Answer:  In Java, interfaces give many of the features of multiple inheritance without many of the problems.  In particular, a class can implement multiple interfaces, which allows objects to be of several different types.  Since all the methods are abstract in the interfaces, however, there is no ambiguity when methods appear in different interfaces with the same name.

9)  Can references to interface types be polymorphic?  Explain.

Answer:  Yes they can.  Hierarchies can be created by implementing interfaces in the same way that they can be created by extending classes.  Polymorphism is the same in either case.

10)  Write an interface for a CD player.  It should have the standard operations (i.e. play, stop, etc) that usual CD players have.

Answer:

public interface CDPlayer  {

public void play();

public void stop();

public void nextTrack();

public void previousTrack();

9Addison­Wesley © 2007

Java Foundations: Introduction to Program Design & Data StructuresJohn Lewis, Peter J. DePasquale, Joseph Chase

Test Bank: Chapter 9

public void seekForward();

public void seekBackwards();}

11)  Give an example of a class that implements the Comparable interface, and explain how the implementation of the compareTo method determines its return value.

Answer:  The String class implements the Comparable interface.  The comparison is based on the lexicographic ordering of String objects defined by the Unicode character set.

12)  Describe the Iterator interface.

Answer:  The Iterator interface provides a method of moving through a collection of objects one at a time.  It includes the next method which returns the next element in the collection and the hasNext method which returns true only if there is another element in the collection.

13)  Give an example of a class that implements the Iterator interface.

Answer:  The Scanner class implements the Iterator interface.

14)  Suppose you are implementing the comparable interface in a class representing a Person, where the ordering is based on the age of the person.  Write a compareTo method for this class.  You may assume that there is an instance variable called age and a method called getAge.

Answer:

public int compareTo(Object o)  {Person p = (Person) o;return this.getAge() ­ p.getAge();

}

15)  Why can't an interface be instantiated? 

Answer:  An interface cannot be instantiated because, similar to an abstract class, it only contains abstract methods.

10Addison­Wesley © 2007