Sie sind auf Seite 1von 14

Chapter 7: Inheritance

Test Bank
Multiple Choice Questions:
For questions 1 4, use the following partial class definitions:
public class A1
{
public int x;
private int y;
public int z;

}
public class A2 extends A1
{
public int a;
private int b;

}
public class A3 extends A2
{
private int q;

}
1)

Which of the following is true with respect to A1, A2 and A3?


a) A1 is a subclass of A2 and A2 is a subclass of A3
b) A3 is a subclass of A2 and A2 is a subclass of A1
c) A1 and A2 are both subclasses of A3
d) A2 and A3 are both subclasses of A1
e) A1, A2 and A3 are all subclasses of the class A
Answer: b. Explanation: The reserved word extends is used to create a subclass. Since A2 extends A1, A2 is a
subclass of A1. Since A3 extends A2, A3 is a subclass of A2.
2)

Which of the following lists of instance data are accessible in class A2?
a) x, y, z, a, b
b) x, y, z, a
c) x, z, a, b
d) z, a, b
e) a, b
Answer: c. Explanation: Class A2 has access to all of its own instance data (a, b) and any instance data from A1 that
were protected (z). Further, all classes, including A2, have access to A1s x since it is public, so x, z, a and b are
accessible in A2.
3)

Which of the following lists of instance data are accessible in A3?


a) x, y, z, a, b, q
b) a, b, q
c) a, q
d) x, z, a, q
e) x, a, q
Answer: d. Explanation: Obviously q is accessible in A3. Also, A3 has access to anything inherited from A2, which
is a. Additionally, since A2 inherits z from A1, it is also inherited by A3. Finally, since x is public, it is visible to all
classes.
TB 71

TB 72

Lewis/Loftus/Cocking, 2/e: Chapter 7 Test Bank

4)

Which of the following is true regarding the use of instance variable y of class A1?
a) it is accessible in A1, A2 and A3
b) it is accessible in A1 and A2
c) it is accessible only in A1
d) it is accessible only in A3
e) it is not accessible to any of the three classes
Answer: c. Explanation: Because it is declared as a private instance data, it is not inherited by any subclasses, and
therefore y is only accessible in the class it was defined, A1.
5)

The instruction super( ); does which of the following?


a) calls the method super as defined in the current class
b) calls the method super as defined in the current class parent class
c) calls the method super as defined in java.lang
d) calls the constructor as defined in the current class
e) calls the constructor as defined in the current class parent class
Answer: e. Explanation: The instruction super represents an invocation of something in the current class parent class.
Since there is no message but merely super( ), it is an invocation of the parent class constructor.
6)

Inheritance through an extended (derirved) class supports which of the following concepts?
a) interfaces
b) modularity
c) information hiding
d) code reuse
e) correctness
Answer: d. Explanation: By extending a class and inheriting from it, the new class does not have to reimplement any
of those inherited methods or instance data, thus saving the programmer an effort. So, code reuse is the ability to reuse
someone elses code for your benefit by extending it for your need.
7)

Which of the following is an example of multiple inheritance?


a) a computer can be a mainframe or a PC
b) a PC can be a desktop or a laptop
c) a laptop is both a PC and a portable device
d) a portable device is a lightweight device
e) Macintosh and IBM PC are both types of PCs
Answer: c. Explanation: Multiple inheritance means that a given class inherits from more than one parent class. Of
those listed above, a laptop computer inherits properties from both PCs and portable devices. The answers in a, b and e
are all examples of single inheritance where a class has at least two children (in a, computer has children mainframe and
PC, in b, PC has children desktop and laptop, in e, PC has children Macintosh and IBM PC). Answer d denotes a
property of a class.
8)

Java does not support multiple inheritance, but some of the abilities of multiple inheritance are available by
a) importing classes
b) implementing interfaces
c) overriding parent class methods
d) creating aliases
e) using public rather than protected or private modifiers
Answer: b. Explanation: Since a class can implement any number of interfaces, that class is in essence using the
interface classes as if those interfaces were defined in this class. So, this class is inheriting the methods and constants of
the interfaces. Further, the class could extend another class and thus inherit directly and indirectly from multiple
classes. This is not the exact same as multiple inheritance, but it is as close as Java comes to that concept.
9)

All classes in Java are directly or indirectly subclasses of the _______ class.
a) Wrapper
b) String
c) Reference
d) this
e) Object

Lewis/Loftus/Cocking, 2/e: Chapter 7 Test Bank

TB 73

Answer: e. Explanation: Java requires that all classes having a parent class. If a class does not extend another class,
then it, by default, extends the Object class. So the Object class is the parent or ancestor of every other class in Java.
10)

Which of the following is not a method of the Object class?


a) hashCode
b) compareTo
c) equals
d) toString
e) all of the above are methods of the Object class
Answer: b. Explanation: The Object class defines clone to create a copy of any object, equals to determine if two
objects are the same object, and toString to translate an Object into a String. However, compareTo is not implement by
Object and must be explicitly implemented in any class that wants to implement the Comparable interface.
11)

Abstract methods are used when defining


a) interface classes
b) derived classes
c) classes that have no constructor
d) arrays
e) classes that have no methods
Answer: a. Explanation: An interface is a class that has defined some of its components, but leaves other components
(methods) for you to implement. So, these components (methods) are referred to as abstract and defined in the interface
class as abstract.
For questions 12 14, consider the following class definition:
public class AClass
{
private int x;
private int y;
public AClass(int a, int b)
{
x = a;
y = b;
}
public int addEm( )
{
return x + y;
}
public void changeEm( )
{
x++;
y--;
}
public String toString( )
{
return + x + + y;
}
}
12)

Consider that you want to extend AClass to BClass. BClass will have a third int instance variable, z. Which of
the following would best define BClass constructor?
a) public BClass(int a, int b, int c)
{
super(a, b, c);

TB 74

Lewis/Loftus/Cocking, 2/e: Chapter 7 Test Bank

}
b) public BClass(int a, int b, int c)
{
x = a;
y = b;
z = c;
}
c)

public BClass(int a, int b, int c)


{
z = c;
}

d) public BClass(int a, int b, int c)


{
super(a, b);
z = c;
}
e) public BClass(int a, int b, int c)
{
super( );
}
Answer: d. Explanation: Inheritance is useful because it allows you to reuse code. For this problem, you would want
to reuse as much of AClass as possible. Answer d allows you to use AClass constructor, which expects two int
parameters. This sets x and y to be a and b respectively. But since AClass does not have an instance data z, you need to
directly assign z to be c in the constructor. The answers in a and e are syntactically invalid since they do not pass the
correct number of parameters to AClass constructor. Finally, the answer in c only sets z correctly and leaves x and y
uninitialized.
13)

You want addEm to now add all three values and return the sum and changeEm to change x and y, but leave z
alone. Which should you do?
a) Redefine addEm and changeEm without referencing super.addEm( ) or super.changeEm( )
b) Redefine addEm to return the value of z + super.addEm( ), but leave changeEm alone
c) Redefine changeEm to call super.changeEm( ) and then set z = x + y, but leave addEm alone
d) Redefine addEm to return the value of z + super.addEm( ) and redefine changeEm to call
super.changeEm( ) and then set z = x + y
e) Redefine changeEm to call super.changeEm( ) without doing anything to z, and redefine addEm to
return super.addEm( )
Answer: b. Explanation: Since super.changeEm( ) will not affect z and we dont want changeEm to affect z, there is
no need to redefine changeEm for BClass. Any reference to changeEm( ) will reference AClass version which is the
same one that BClass will use. But addEm needs redefining because the inherited method addEm calls AClass addEm
which only adds x and y together. Now, we want to add x, y and z together. We can either redefine addEm entirely, or
use super.addEm( ) and add z to the value returned. The latter approach is better since it reuses previously written code.

14)

Which of the following would best redefine the toString method for BClass?
a) public String toString(int z)
{
return + x + + y + + z;
}

Lewis/Loftus/Cocking, 2/e: Chapter 7 Test Bank

TB 75

b) public String toString( )


{
return super.toString( );
}
c)

public String toString( )


{
return super.toString( ) + + z;
}

d) public String toString( )


{
return super.toString( ) + x + + y + + z;
}
e)

public String toString( )


{
return + x + + y + + z;
}
Answer: c. Explanation: The best way to redefine a method is to reuse the parent class method and supplement it with
the code needed to handle the changes in the subclass. Answer c does this. Answer b returns only x and y, not z, while
answer a is syntactically invalid because the toString method does not accept a parameter.
15)

Which of the following is true regarding Java classes?


a) All classes must have 1 parent but may have any number of children (derived or extended) classes.
b) All classes must have 1 child (derived or extended) class but may have any number of parent classes.
c) All classes must have 1 parent class and may have a single child (derived or extended) class.
d) All classes can have any number (0 or more) of parent classes and any number of children (derived or
extended) classes.
e) All classes can have either 0 or 1 parent class and any number of children (derived or extended)
classes.
Answer: a. Explanation: Java supports inheritance but not multiple inheritance, so a Java class can have any number
of children but only one parent. Further, since all Java classes inherit either directly or indirectly from the Object class,
all Java classes have exactly 1 parent class.
16)

Two children of the same parent class are known as


a) aliases
b) relatives
c) clones
d) brothers
e) siblings
Answer: e. Explanation: The relationship between two children of the same parent is referred to as siblings (brothers
would imply a gender). Clones are copies of the same object and aliases are the same object. Brothers and relatives are
not used to define relationships between classes in Java.
17)

A variable declared to be of one class can later reference an extended class of that class. This variable is
known as
a) public
b) derivable
c) cloneable
d) polymorphic
e) none of the above, a variable declared to be of one class can never reference any other type of class,
even an extended class
Answer: d. Explanation: The term polymorphic means that the variable can have many forms. Under ordinary
circumstances, Java is strongly defined that is, a variable, once declared to be of a type, can never change to be of a

TB 76

Lewis/Loftus/Cocking, 2/e: Chapter 7 Test Bank

different type. The exception to this is that polymorphic variables can be any type of derived class (although not at the
same time, the variable can change from one type to another).
18)

In order to determine the type that a polymorphic variable refers to, the decision is made
a) by the programmer at the time the program is written
b) by the compiler at compile time
c) by the operating system when the program is loaded into memory
d) by the Java run-time environment at run time
e) by the user at run time
Answer: d. Explanation: The polymorphic variable can take on many different types, but it is not know which type it
has taken on until the program is executing. At the time the variable is referenced, then the decision must be made.
That decision is made by the run-time environment based on the latest assignment of the variable.
For questions 19 21, assume that Student, Employee and Retired are all subclasses of Person, and all four classes have
different implementations of the method getMoney. Consider the following code where are the required parameters
for the constructors:
Person p = new Person();
int m1 = p.getMoney( );
// assignment 1
p = new Student();
int m2 = p.getMoney( );
// assignment 2
if (m2 < 100000) p = new Employee();
else if (m1 > 50000) p = new Retired();
int m3 = p.getMoney( );
// assignment 3
19)

The reference to getMoney( ) in assignment 1 is to the class


a) Person
b) Student
c) Employee
d) Retired
e) this cannot be determined by examining the code
Answer: a. Explanation: At this point of the program, p is a Person, and so getMoney is a reference to Persons
getMoney method.
20) The reference to getMoney( ) in assignment 2 is to the class
a) Person
b) Student
c) Employee
d) Retired
e) this cannot be determined by examining the code
Answer: b. Explanation: At this point of the program, p is a Student, and so getMoney is a reference to Students
getMoney method.
21) The reference to getMoney( ) in assignment 3 is to the class
a) Person
b) Student
c) Employee
d) Retired
e) this cannot be determined by examining the code
Answer: e. Explanation: Because there is no way to know if (m2 < 100000) is true or false or if (m1 > 50000) is true
or false, it is not known whether p is still a reference to Student or if p now references an Employee or a Retired, and
therefore the reference to getMoney( ) may be to Student, Employee or Retired, but we cannot tell which one just by
examining the code.
22) The relationship between a child class and a parent class is referred to as a(n) ____ relationship.
a) has-a
b) is-a
c) was-a

Lewis/Loftus/Cocking, 2/e: Chapter 7 Test Bank

TB 77

d) instance-of
e) alias
Answer: b. Explanation: The term is-a is used to express that a subclass is a type of parent class. For instance, a
GraduateStudent is a type of Student. The subclass is a more specific type. The has-a relationship refers to the
attributes or elements of a class (for instance, a Student has a GPA) and instance-of refers to the relationship between a
class and an instantiated object of that class. There is no such thing as a was-a relationship and an alias denotes two
variables that reference the same object or instance.
For questions 23 24, consider the following class definition:
public class Q
{
private int x;
public Q(int newValue)
{
x = newValue;
}
}
23) Which of the following is true about the class Q?
a) it has no parent class
b) its parent class is Object
c) its parent class is Java
d) it cannot be extended
e) it has a default child called Object
Answer: b. Explanation: The class does not explicitly extend any class, so it does not have a specified parent class.
But all Java classes must have a parent, which defaults to Object if not specified. So, Q is a child class of Object.
24) If q1 and q2 are objects of Q, then q1.equals(q2)
a) is a syntax error since equals is not defined in the Q class
b) is true if q1 and q2 both store the same value of x
c) is true if q1 and q2 reference the same Q object
d) is never true
e) throws a NullPointerException
Answer: c. Explanation: Q is a subclass of the Object class. The Object class has an equals method that does the same
as = =, that is, returns true if two variables reference the same object.
25) A mouse event is a(n)
a) listener
b) object
c) interface
d) GUI component
e) all of the above
Answer: b. Explanation: Mouse events are objects of the class MouseEvent. MouseEvent has its own instance data
that describe the mouse event such as where the mouse was when the event occurred and if the button was pressed,
released, etc. MouseEvent has a number of methods such as returning the X or Y coordinate or Point of the mouse, and
the number of clicks performed for this mouse event.
True/False Questions:
1) Clicking the mouse button generates three mouse events, mousePressed, mouseClicked, and mouseReleased.
Answer: True. Explanation: While pressing the mouse button only generates mousePressed and releasing the button
only generates mouseReleased, if the pressing and releasing are done quickly, then it represents a clicking action and so
all three events are generated.

TB 78

Lewis/Loftus/Cocking, 2/e: Chapter 7 Test Bank

2) A derived class has access to all of the methods of the parent class, but not to any of the instance data of the parent
class.
Answer: False. Explanation: Since methods can be declared as private, any private methods are not accessible by a
derived class. Furthermore, any public (or protected) instance variables are accessible in a derived class.
3) If class AParentClass has a public instance variable x, and AChildClass is a derived class of AParentClass, then
AChildClass can access x but cannot redefine x to be a different type.
Answer: False. Explanation: A derived class can redefine any of the instance data or methods of the parent class. The
parent class version is now hidden, but can be accessed through the use of super, as in super.x.
Consider the following class hierarchy and answer questions 4 7.
X

4) A is a derived class of X.
Answer: False. Explanation: While A is a descendant of class X, it is not a derived class. Instead, X is a derived class
of Y and Y is a derived class of X. A ultimately inherits items from X as long as those items were not overridden by Y.
5) Y is a derived class of Z.
Answer: False. Explanation: Y and Z are known as siblings because they are children of the same parent, but Y and Z
may have nothing in common other than what they both inherit from X.
6) If A, B, Y and Z all contain the same instance data d1, then d1 should be declared in X and inherited into Y, Z, A
and B.
Answer: True. Explanation: Anything in common between A, B, Y and Z should be declared in X to properly identify
that it is a class trait common amongst them. That is, common elements should be defined as high up in the hierarchy as
possible. If all descendants of X have the trait (instance data) d1, then it is part of X too.
7) B can use any public methods defined in X (that are not overridden by Y).
Answer: True. Explanation: Y inherits methods from X, and B inherits them from Y.
8) If classes C1 and C2 both implement an interface Cint, which has a method whichIsIt, and if Cint c = new C1( ); is
performed at one point of the program, then a later instruction c.whichIsIt( ); will invoke the whichIsIt method
defined in C1.
Answer: False. Explanation: Because C1 and C2 implement the same interface, they both implement whichIsIt. The
variable c is known as a polymorphic variable, meaning that it can change from being an C1 to a C2. So, the message
c.whichIsIt( ); may invoke C1s whichIsIt or C2s whichIsIt. There is no way to tell until run-time.
For questions 9 13, assume that Poodle and Retriever are derived classes of Dog and that Dog d = new Dog(),
Poodle p = new Poodle(), and Retriever r = new Retriever(); where the are the necessary parameters for the
classes.
9) The assignment statement d = p; is legal even though d is not a Poodle.
Answer: True. Explanation: Since Poodle extends Dog, Dog is a wider class (Poodle is more specific, and therefore
narrower). An assignment statement can assign a narrower item into a wider variable (since p is narrower, it can be
assigned to d).

Lewis/Loftus/Cocking, 2/e: Chapter 7 Test Bank

TB 79

10) The assignment statement p = d; is legal even though p is not a Dog.


Answer: False. Explanation: Since Poodle extends Dog, Dog is known as a wider class (Poodle is more specific, and
therefore narrower). In any assignment statement, it is possible to take a narrower item and assign it into a wider
variable, but it is not possible to assign a wider item into a narrower variable. To accomplish this, a cast must be
explicitly made. So, the statement p = d; is illegal although the statement p = (Poodle) d; would be legal.
11) The assignment Object o = p; is legal.
Answer: True. Explanation: Every object descends from the Object class, so any kind of object reference can be
assigned to a variable that refers to an Object.
12) The statements d = p; d = r; demonstrate polymorphism.
Answer: True. Explanation: A polymorphic reference is one that can refer to different types of objects at different
times. The reference d refers to a Poodle after the first assignment, and to a Retriever after the second assignment.
13) The statement r = (Retriever)p; is valid.
Answer: False. Explanation: p refers to a Poodle which is not a Retriever and so cannot be cast to a Retriever.
14) Inheritance allows us to create a new class from an existing class.
Answer: True. Explanation: This is a powerful technique that allows us to reuse software.
15) When using inheritance, the relationship between the child and the parent should be a has-a relationship.
Answer: False. Explanation: The relationship should be an is-a relationship. The is the child is-a parent. For example,
a Poodle is-a Dog.
16) The word super is used to refer to the parent class.
Answer: True. Explanation: super can be used to call the constructor and methods of the parent class.
17) In Java, each child class can have only one parent.
Answer: True. Explanation: This is called single inheritance and it is the approach used in Java (as opposed to multiple
inheritance).
18) When a child defines a method with the same signature as a method in the parent, this is called method overloading.
Answer: False. Explanation: Method overloading is two methods in the same class that have the same name but
different parameters. When a child defines a method with the same signature as a method in the parent, this is called
method overriding.
19) The following two class definitions are equivalent:
class Foo {
// anything
}
class Foo extends Object {
// anything
}
Answer: True. Explanation: If a class definition does not have an "extends" then it automatically inherits directly from
Object.
20) Every object in Java, no matter what class it came from, has a method called toString.
Answer: True. Explanation: The toString method is on the Object class, which every other object in Java descends
from.
21) The equals method will always return false when comparing two objects of different classes.
Answer: False. Explanation: The equals method can be implemented in any way for a given class. The programmer
could implement it so as to always return true, for example.

TB 80

Lewis/Loftus/Cocking, 2/e: Chapter 7 Test Bank

22) An abstract class can only be instantiated if at least half of its methods are defined.
Answer: False. Explanation: An abstract class can never be instantiated.
23) Abstract classes are typically defined at the bottom of a class hierarchy.
Answer: False. Explanation: Abstract classes are usually defined near the top of a class hierarchy. They cannot be at
the very bottom because they cannot be instantiated. Abstract classes are only useful in being parents classes to other
classes.
24) Suppose Letter is an abstract class with an abstract method called hello, and R is a class that extends Letter and
does not contain a definition for a method called hello in the class. If myR is an instance of R, then myR.hello()
is legal assuming includes the correct parameters.
Answer: False. Explanation: Since hello is an abstract method and R does not define it, it is an abstract method in R as
well, which means that R must be an abstract class and therefore cannot be instantiated. If R was not declared abstract,
then compiling it would result in an error.
25) Polymorphism works with inheritance only; it does not work with interfaces.
Answer: False. Explanation: Polymorphism occurs with interfaces as well.
Free-Form Questions:
1) An applet implements MouseListener, and has int instance data x and y. These variables will be the (X, Y)
coordinates of where the mouse is clicked. Every time the mouse is clicked, draw a 40x40 Oval centered around x
and y. Write the mouseClicked and paint methods to draw the Oval every time the mouse is clicked.
Answer:
public void mouseClicked(MouseEvent me)
{
x = me.getX( );
y = me.getY( );
repaint( );
}
public void paint(Graphics page)
{
page.setColor(Color.black);
page.drawOval(x - 20, y 20, 40, 40);
}
2) An Applet implements MouseMotionListener. Write the mouseMoved and paint methods for an applet that will
display the location of the mouse as an (x, y) coordinate. The output should be given at location (10, 10) of the
applet no matter where the mouse is.
Answer:
public void mouseMoved(MouseEvent me)
{
x = me.getX( );
y = me.getY( );
repaint( );
}
public void paint(Graphics page)
{
page.setColor(Color.black);
page.drawString(Mouse Location: + x + + y, 10, 10);
}
3) An Applet implements MouseMotionListener. Write the mouseMoved and paint methods for an applet that will
display the location of the mouse as an (x, y) coordinate. The output should be given at the current mouse location.

Lewis/Loftus/Cocking, 2/e: Chapter 7 Test Bank

TB 81

Answer:
public void mouseMoved(MouseEvent me)
{
x = me.getX( );
y = me.getY( );
repaint( );
}
public void paint(Graphics page)
{
page.setColor(Color.black);
page.drawString(Mouse Location: + x + + y, x, y);
}
4) An Applet implements MouseMotionListener and is 600x600 in size. Write a mouseMoved method so that if the
mouse is moved into the upper left hand quadrant of the Applet, the entire applet turns blue, if the mouse is moved
into the upper right hand quadrant of the Applet, the entire applet turns yellow, if the mouse is moved into the
lower left hand quadrant of the Applet, the entire applet turns green, and if the mouse is moved into the lower right
hand quadrant of the Applet, the entire applet turns red.
Answer:
public void mouseMoved(MouseEvent me)
{
x = me.getX( );
y = me.getY( );
if(x >= 0 && x < 300 && y >= 0 && y < 300) setBackground(Color.blue);
else if(x >= 0 && x < 300 && y >= 300 && y < 600) setBackground(Color.green);
else if(x >= 300 && x < 600 && y >= 0 && y < 300) setBackground(Color.yellow);
else if(x >= 300 && x < 600 && y >= 300 && y < 600) setBackground(Color.red);
}
5) If a class extends Applet and also implements MouseListener and MouseMotionListener, what methods must be
declared in this class?
Answer: MouseListener requires mousePressed, mouseClicked, mouseReleased, mouseEntered and mouseExited.
MouseMotionListener requires mouseMoved and mouseDragged. Applet does not require any particular methods.
6) Consider a class Plane and three subclasses, Glider, PropPlane and Jet. What instance data should be declared in
Plane and what instance data should be declared in one of the three subclasses. Come up with at least 2 instance
data unique to each of the four classes given.
Answer: Plane might include instance data such as size, weight, age, cost, carryingCapacity and maxSpeed. Glider
might have instance data of maxAltitude and amountOfWindNeeded, PropPlane might have instance data of typeOfFuel
and numberOfProps and Jet might have instance data of typeOfFuel, numberOfNacelles, and minimumSpeed.
7) Assume a class Triangle has been defined. It has three instance data, Point p1, p2, p3. The class also has a
constructor that receives the 3 Points and initializes p1, p2, and p3, a toString method that outputs the 3 Points, and
a computeSurfaceArea method that calculates the surface area of the Triangle (as an int value). We want to extend
this class to represent a 3-dimensional Pyramid, which consists of 4 Points. Since the Pyramid will consist of in
essence, 4 triangles, computeSurfaceArea for the Pyramid will compute 4 * the surface area of the Triangle made
up of 3 of those 4 Points. Write the Pyramid class to handle the difference(s) between a Pyramid and the previously
defined Triangle. Assume the instance data of Triangle are protected and all methods are public. Also assume that
the class Point has a toString method.
Answer:
public class Pyramid extends Triangle
{
private Point p4;
public Pyramid(Point a1, Point a2, Point a3, Point a4)
{

TB 82

Lewis/Loftus/Cocking, 2/e: Chapter 7 Test Bank

super(a1, a2, a3);


p4 = a4;
}
public String toString( )
{
super.toString( ) + p4.toString( );
}
public int computeSurfaceArea( )
{
return 4 * super.computeSurfaceArea( );
}
}
8) Explain the difference between implementing an interface and a derived class.
Answer: Implementing an interface involves implementing all the methods declared in the interface. When you create a
derived class, the methods of the parent class are inherited and dont need to be reimplemented (unless they are declared
abstract). The methods of a parent class, may, however, be overridden (reimplemented) by a derived class.
9) Explain the difference between using an imported class and extending a class.
Answer: An imported class lets you use someone elses code, but only as it was intended for use. You have no access
to members that are not declared public. An extended class allows you to reuse someone elses code, but you can
modify it to work as you wish, and you gain access to members that were declared protected as well as anything that
was declared public.
10) Write the init and paint methods of an Applet and the methods needed to implement MouseMotionListener so that
the applet can draw a point on the applet for every mouse position as the mouse is being moved on the screen. Use
a 2-D array of ints to represent the X and Y coordinates of the mouse as it is being moved. For instance,
point[0][0] and point[0][1] represent the X and Y coordinates of the mouse at its first position. The paint method
will need to be called every time the mouse is moved and all points redrawn on the applet.
Answer:
public class MouseFollower extends Applet implements MouseMotionListener
{
private int[ ][ ] points;
private int numPoints;
public void init( )
{
numPoints = 0;
points = new int[1000][2];
setBackground(Color.blue);
addMouseMotionListener(this);
}
public void paint(Graphics page)
{
page.setColor(Color.red);
for(int j = 0; j<numPoints; j++)
page.drawOval(points[j][0], points[j][1], 1, 1);
}
public void mouseMoved(MouseEvent me)
{
if(numPoints < 1000)

Lewis/Loftus/Cocking, 2/e: Chapter 7 Test Bank

TB 83

{
points[numPoints][0] = me.getX();
points[numPoints][1] = me.getY();
numPoints++;
}
repaint( );
}
public void mouseDragged(MouseEvent me) { }
}
11) Assume the class Student implements the Speaker interface from the textbook. Recall that this interface includes
two abstract methods, speak( ) and announce(String str). A Student contains one instance data, String classRank.
Write the Student class so that it implements Speaker as follows. The speak method will output I am a newbie
here if the Student is a Freshman, I hate school if the Student is either a Sophomore or a Junior, or I can
not wait to graduate if the student is a Senior. The announce method will output I am a Student, here is what I
have to say followed by the String parameter on a separate line. Finally, the classRank is initialized in the
constructor. Only implement the constructor and the methods to implement the Speaker interface.
Answer:
public class Student implements Speaker
{
private String classRank;
public Student(String cr)
{
classRank = cr;
}
public void speak( )
{
if(cr.equals(Freshman))
System.out.println(I am a newbie here);
else if (cr.equals(Sophomore) | | cr.equals(Junior))
System.out.println(I hate school);
else if(cr.equals(Senior))
System.out.println(I can not wait to graduate);
}
public void announce(String str)
{
System.out.println(I am a Student, here is what I have to say);
System.out.println(str);
}
}
Consider the class Car and the subclass SportsCar. Car has instance data of currentSpeed, type, year, cost, model, color
and methods of accelerate, brake, getGasMileage, getInsuranceRate and determineSpeed. Use this information to
answer questions 12 13.
12) What instance data and methods might you define for SportsCar that are not part of Car?
Answer: A sports car may have a racing stripe, which could be stored in a boolean variable, and a maxSpeed, also the
number of gears. So the SportsCar class might add instance data of stripe, maxSpeed and numberGears. There might
be methods to determine how safe the SportsCar is and whether it could win a race or not against another SportsCar.
13) What methods inherited from Car should SportsCar override?

TB 84

Lewis/Loftus/Cocking, 2/e: Chapter 7 Test Bank

Because a SportsCar will have different acceleration, the accelerate method should be overridden. Also,
determineSpeed might change as will getInsuranceRate. The brake method may or may not differ and getGasMileage
will probably stay the same.
14) A motorcycle inherits properties from both a bicycle and a car. Java does not permit multiple inheritance. Assume
that Bicycle and Car have both been declared. Explain how you might go about implementing a Motorcycle as a
derived class.
Answer: You should extend whichever class is closer to the Motorcycle. For instance, both Motorcycle and Bicycle are
two-wheeled vehicles and if this attribute is more important than other attributes, it might make sense to extend Bicycle.
However, because Motorcycle shares internal combustion engine, gas fuel, similar speed and driving capabilities to a
Car, it would probably make more sense to inherit from Car and override those methods that are most different (for
instance, gasMileage varies greatly between cars and motorcycles). The Motorcycle derived class would then inherit
the above instance data and methods to calculate and access these values. However, because the Motorcycle is also
significantly different from a Car, other instance data and methods would need to be added and some methods
redefined. For instance, a mechanism to determine how safe a Car is will differ from a mechanism in determining a
Motorcycles safety.
15) Consider a class Name, which has four instance data (all Strings): first, middle, last and title. Even though Name
inherits the equals method from Object, it would make more sense to override it. Why?
Answer: Objects version of equal compares two objects to see if they are the same Object, not if they are two Objects
that share the same information. Two Name objects should be considered equal if they share the same first, middle, last
and title Strings, not just if they are aliases for the same Name in memory. Therefore, the equals method should be
overridden.

Das könnte Ihnen auch gefallen