10.11. Multiple-Choice Exercises¶
10.11.1. Easier Multiple Choice Questions¶
- Initialize the fields in the object.
- A constructor is often used to initialize the fields to their default values or in the case of a parameterized constructor, to the values passed in to the constructor.
- Determines the amount of space needed for an object and creates the object.
- The object is already created before the constructor is called.
- Names the new object.
- Constructors do not name the object.
10-11-1: What best describes the purpose of a class’s constructor?
- The methods do different things.
- Methods that do different things should be named differently.
- The methods have different parameter names.
- There is no reason the parameter names ought to be different if the two methods are performing the same action.
- The methods have different post-conditions.
- If the methods have different post-conditions, they are performing different functions, and should be named differently.
- Two methods with the same name can never be included in the same class.
- If two methods perform the same function, they can be named the same. However, the number of parameters, type of parameters, or order of parameter types must be different.
- The methods have different numbers of parameters
- Overloading occurs when two methods perform the same essential operation, but take a different number and/or type of parameters.
10-11-2: Under which of these conditions is it appropriate to overload a method (ie: the class will contain two methods with the same name)?
- Use four unrelated classes:
Car
,Doors
,AirConditioning
, andMilesPerGallon
. - Only
Car
should be a class. The number of doors, flag if it has air conditioning, and the average number of miles per gallon are attributes of a car so they belong in aCar
class. - Use a class
Car
with three subclasses:Doors
,AirConditioning
, andMilesPerGallon
. - Doors, air conditioning, and miles per gallon are not a kind of car. Child classes need to be able to be substituted for the parent class.
- Use a class
Car
, with fields:numDoors
,hasAir
, andmilesPerGallon
. - The number of doors, flag if it has air conditioning, and the average number of miles per gallon are attributes of a car. Each of these is a simple value so they can just be fields of a
Car
class. - Use a class
Car
, with subclasses ofDoors
,AirConditioning
, andMilesPerGallon
. - A door is not a type of car. A flag for air conditioning is not a type of door, and a miles per gallon is not a type of air conditioning flag. Child classes need to be able to be substituted for the parent class.
- Use classes:
Doors
,AirConditioning
, andMilesPerGallon
, each with a subclassCar
. - A class
Car
can't be a subclass of three different classes. Each class can only have one parent class. Also a car is not a type of door, air conditioning flag, or miles per gallon. Child classes need to be able to be substituted for the parent class.
10-11-3: A car dealership needs a program to store information about the cars for sale. For each car, they want to keep track of the following information: number of doors (2 or 4), whether the car has air conditioning, and its average number of miles per gallon. Which of the following is the best design?
- How the methods are implemented.
- Only the programmer of the
Employee
class must know how the public methods work. The programmer that is using theEmployee
class can just use the public methods and not worry about how they are implemented. - The method names.
- The programmer who writes the methods will need to know what the names are. The programmer who will use the public methods will also need to know the names of the methods in order to invoke them.
- The method return types.
- In order to use the public methods of the
Employee
class, a programmer must know the method return types. - Constants
- Constants are public fields and are meant to be used by people using a class.
- The number and types of the method parameters.
- In order to use the public methods of the
Employee
class, a programmer must know the number of parameters and the type for each parameter.
10-11-4: A program is being written by a team of programmers. One programmer is implementing a class called Employee
; another programmer is writing code that will use the Employee
class. Which of the following aspects of the public methods and fields of the Employee
class does not need to be known by both programmers?
- Create one class
PublishedMaterial
with the requested fields plus type. - This will complicate the process of retrieving objects based on their type. Also if we need to add information that is specific to
Book
orMovie
orAudioTape
it would be best if these were subclasses ofPublishedMaterial
. - Create classes
Book
,Movie
, andAudioTape
with the requested fields. - This involves writing more code than is necessary (usually people copy and paste the shared code) and makes it harder to fix errors. It would be better to put common fields and methods in the superclass
PublishedMaterial
and haveBook
,Movie
, andAudioTape
be subclasses. - Create one class
BookStore
with the requested fields plus type. - The class name,
BookStore
, seems to imply the thing that keeps track of the store. This would be an appropriate class name for an object that handles the items in theBookstore
. However, for the published material, it would be better to use a superclassPublishedMaterial
and subclasses forBook
,Movie
andAudioTape
. - Create classes for each.
- This is more classes than is necessary. Items such as
Title
,Price
,ID
,Author
andDatePublished
are simple variables that do not need a class of their own but should be fields in aPublishedMaterial
superclass, withMovie
,AudioTape
andBook
as subclasses. - Create the class
PublishedMaterial
with children classes ofBook
,Movie
, andAudioTape
. - We will need to get objects based on their type so we should create classes for
Book
,Movie
, andAudioTape
. They have common fields so we should put these in a common superclassPublishedMaterial
.
10-11-5: A bookstore is working on an on-line ordering system. For each type of published material (books, movies, audio tapes) they need to track the id, title, author(s), date published, and price. Which of the following would be the best design?
10.11.2. Medium Multiple Choice Questions¶
- Won't compile since
GradStudent
doesn't have agetInfo
method GradStudent
will inherit thegetInfo
method fromStudent
. This would be true ifgetInfo
was a private method.- Taco
- Objects know what class they are created as and all methods are resolved starting with that class at run time. If the method isn't found in that class the parent class is checked (and so on until it is found). So it will first look for
getInfo
inGradStudent
and when it doesn't find it it will look inStudent
. IngetInfo
it callsthis.getFood
. Again, it will first look for this method inGradStudent
. It will find thegetFood
method there and return "Taco". - Pizza
- This would be true if it was
Student s1 = new Student();
- Won't compile since you are creating a
GradStudent
, not aStudent
- An object of a subclass can be substituted for a parent class object. A
GradStudent
is aStudent
. - Won't compile since you use
this.getFood()
- In object methods if you leave off the
this.
when invoking an object method it will be added for you by the compiler. The keywordthis
refers to the current object which is implicitly passed to all object methods.
10-11-6: Given the following class declarations, what is the output from Student s1 = new GradStudent();
followed by s1.getInfo();
?
public class Student {
public String getFood() {
return "Pizza";
}
public String getInfo() {
return this.getFood();
}
}
public class GradStudent extends Student {
public String getFood() {
return "Taco";
}
}
- I only
- I is wrong because
y
is a private field and thus can not be directly accessed from code in a client class. - II only
- I is wrong because
y
is a private field and thus can not be directly accessed from code in a client class. II is correct becauseEnhancedItem
hassetY
as a public method. III is correct becauseEnhancedItem
inherits the public methodsetX
fromItem
. - I and II only
- I is wrong because
y
is a private field and thus can not be directly accessed from code in a client class. - II and III only
- I is wrong because
y
is a private field and thus can not be directly accessed from code in a client class. II is correct becauseEnhancedItem
hassetY
as a public method. III is correct becauseEnhancedItem
inherits the public methodsetX
fromItem
. - I, II, and III
- I is wrong because
y
is a private field and thus can not be directly accessed from code in a client class.
10-11-7: Given the following class declarations, and EnhancedItem enItemObj = new EnhancedItem();
in a client class, which of the following statements would compile?
public class Item
{
private int x;
public void setX(int theX)
{
x = theX;
}
// ... other methods not shown
}
public class EnhancedItem extends Item
{
private int y;
public void setY(int theY)
{
y = theY;
}
// ... other methods not shown
}
I. enItemObj.y = 32;
II. enItemObj.setY(32);
III. enItemObj.setX(52);
- t1.method1(t1,t1);
- You can't pass an object of class
Test1
since it is not either an object of typeTest2
or an object of typeTest3
. You can pass the specified type or an object that is a subclass of the specified type butTest1
is not a subclass ofTest2
orTest3
. - t2.method1(t2,t2);
- You can't pass an object of class
Test2
as a parameter of typeTest3
.Test2
is the parent class ofTest3
not a subclass. You can pass an object of the specified type or an object of any subclass. - t3.method1(t1,t1);
- You can't pass an object of class
Test1
since it is not either an object of typeTest2
or an object of typeTest3
. You can pass the specified type or an object that is a subclass of the specified type butTest1
is not a subclass ofTest2
orTest3
. - t2.method1(t3,t2);
- You can't pass
t2
as an object of typeTest3
since it is an object of classTest2
and classTest2
is not either classTest3
or a subclass of classTest3
. ClassTest2
is the parent of classTest3
. - t3.method1(t3,t3);
- Since
method1
is a public method of classTest1
objects of any subclasses ofTest1
can invoke the method. So, it can be invoked ont3
since it is an object ofTest3
and this is a subclass ofTest1
. And, sincemethod1
takes an object of classTest2
andTest3
as parameters. This actually means it can take an object ofTest2
or any subclass ofTest2
and an object ofTest3
or any subclass ofTest3
. So it can taket3
which is an object of classTest3
as an object ofTest2
sinceTest3
is a subclass ofTest2
.
10-11-8: Given the following class declarations and initializations in a client program, which of the following is a correct call to method1
?
public class Test1
{
public void method1(Test2 v1, Test3 v2)
{
// rest of method not shown
}
}
public class Test2 extends Test1
{
}
public class Test3 extends Test2
{
}
The following initializations appear in a different class.
Test1 t1 = new Test1();
Test2 t2 = new Test2();
Test3 t3 = new Test3();
- Meow Moo Woof Awk Awk
- Objects keep a reference to the class that created them. So, even if you put them in an array of
Animal
objects, they know what they are and all methods are resolved starting with the class of the object.Bird
andPig
do not override speak so thespeak
method inAnimal
will execute. - Awk Awk Awk Awk Awk
- Methods are always resolved starting with the class of the object, so
Cat
,Cow
, andDog
will all execute their overriddenspeak
methods, so the output will be: Meow Moo Woof Awk Awk. - This will not compile
- Because
Bird
,Cow
,Cat
,Dog
, andPig
are subclasses ofAnimal
, they can be stored in an array declared asAnimal
without any compile time errors. - This will have runtime errors
- Because
Bird
,Cow
,Cat
,Dog
, andPig
are subclasses ofAnimal
, they can be stored in an array declared asAnimal
without any runtime errors. - Meow Moo Woof Oink Awk
- The
Pig
class did not override thespeak
method, so it will use the method fromAnimal
, thus the output should be: Meow Moo Woof Awk Awk
10-11-9: If you have a parent class Animal
that has a method speak()
which returns: Awk. Cat
has a speak
method that returns: Meow. Bird
does not have a speak
method. Dog
has a speak
method that returns: Woof. Pig
does not have a speak
method. Cow
has a speak
method that returns: Moo. What is the output from looping through the array a
created below and asking each element to speak()
?
Animal[] a = { new Cat(), new Cow(), new Dog(), new Pig(), new Bird() }
- The code compiles and runs with no errors, the output is 5 6 5 6
RaceCar
, while it inherits methods fromCar
via inheritance, has a separate and different constructor that sets the initial fuel amount to2 * g
, thus in this case,fuel
forfastCar
is set to10
initially.- The code compiles and runs with no errors, the output is: 5 6 10 11
- The code compiles correctly, and because
RaceCar
extends theCar
class, all the public methods ofCar
can be used byRaceCar
objects. Also, a variableCar
can refer to aCar
object or an object of any subclass ofCar
. An object always knows the class that created it, so even thoughfastCar
is declared to be aCar
the constructor that is executed is the one forRaceCar
. - The code compiles and runs with no errors, the output is 10 11 10 11
- The variable
car
is aCar
object, so the constructor used is not the same as thefastCar
object which is aRaceCar
. Thecar
constructor does not change the passed in parameter, so it is set to5
initially. - The code won't compile.
RaceCar
inherits from theCar
class so all the public methods inCar
can be accessed by any object of theRaceCar
class.- You get a runtime error
ClassCastException
, whenfastCar.addFuel()
is executed. RaceCar
inherits from theCar
class so all the public methods inCar
can be accessed by any object of theRaceCar
class.
10-11-10: Given the following class declarations and code, what is the result when the code is run?
public class Car
{
private int fuel;
public Car() { fuel = 0; }
public Car(int g) { fuel = g; }
public void addFuel() { fuel++; }
public void display() { System.out.print(fuel + " "); }
}
public class RaceCar extends Car
{
public RaceCar(int g) { super(2*g); }
}
What is the result when the following code is compiled and run?
Car car = new Car(5);
Car fastCar = new RaceCar(5);
car.display()
car.addFuel();
car.display();
fastCar.display();
fastCar.addFuel();
fastCar.display();
- I only
- Both I and III are correct. I is correct because variable
b
has been declared to be an object of the classBook
so you can invoke any public methods that are defined in theBook
class or in parents ofBook
. II is not correct because you can't invoke methods in theDictionary
class directly onb
sinceb
is declared to be of typeBook
not typeDictionary
andDictionary
is a subclass ofBook
not a parent class ofBook
. III is correct because you can castb
to typeDictionary
and then invoke public methods inDictionary
. - II only
- You can't invoke methods in the
Dictionary
class directly onb
sinceb
is declared to be of typeBook
not typeDictionary
andDictionary
is a subclass ofBook
not a parent class ofBook
. The compiler checks that the method exists on the declared class type, not the run-time type of the object. - I and III only
- I is correct because variable
b
has been declared to be an object of the classBook
so you can invoke any public methods that are defined in theBook
class or in parents ofBook
. II is not correct because you can't invoke methods in theDictionary
class directly onb
sinceb
is declared to be of typeBook
not typeDictionary
andDictionary
is a subclass ofBook
not a parent class ofBook
. III is correct because you can castb
to typeDictionary
and then invoke public methods inDictionary
. - III only
- I is also correct.
- I, II, and III
- You can't invoke methods in the
Dictionary
class directly onb
sinceb
is declared to be of typeBook
not typeDictionary
andDictionary
is a subclass ofBook
not a parent class ofBook
. The compiler checks that the method exists on the declared class, not the run-time class.
10-11-11: Given the following class declarations and code, what is the result when the code is run?
public class Book
{
public String getISBN()
{
// implementation not shown
}
// constructors, fields, and other methods not shown
}
public class Dictionary extends Book
{
public String getDefinition(String word)
{
// implementation not shown
}
// constructors, fields, and methods not shown
}
Assume that the following declaration appears in a client class.
Book b = new Dictionary();
Which of the following statements would compile without error?
I. b.getISBN();
II. b.getDefinition("wonderful");
III. ((Dictionary) b).getDefinition("wonderful");
- Lasagna Meow Screeech
- The baseclass constructor runs first so Animal doesn't have one so then it goes to Cat's constructor and then Garfield's constructor
- Meow Screeech Lasagna
- The baseclass constructor runs first so Animal doesn't have one so then it goes to Cat's constructor and then Garfield's constructor
- Screeech Meow Lasagna
- The baseclass constructor runs first so Animal doesn't have one so then it goes to Cat's constructor and then Garfield's constructor
- Lasagna Screeech Meow
- The baseclass constructor runs first so Animal doesn't have one so then it goes to Cat's constructor and then Garfield's constructor
10-11-12: What is the output of the following code?
class Animal
{
void someSound()
{
System.out.print("Screeech ");
}
}
class Cat extends Animal
{
public Cat()
{
System.out.print("Meow ");
super.someSound();
}
}
class Garfield extends Cat
{
public Garfield()
{
System.out.print("Lasagna ");
}
}
public class MainClass
{
public static void main(String[] args)
{
Garfield garfield = new Garfield();
}
}
10.11.3. Hard Multiple Choice Questions¶
- ABDC
- Even though b is declared as type
Base
it is created as an object of theDerived
class, so all methods to it will be resolved starting with theDerived
class. So themethodOne()
inDerived
will be called. This method first callssuper.methodOne
so this will invoke the method in the superclass (which isBase
). So next themethodOne
inBase
will execute. This prints the letter "A" and invokesthis.methodTwo()
. Sinceb
is really aDerived
object, we check there first to see if it has amethodTwo
. It does, so execution continues in theDerived
classmethodTwo
. This method invokessuper.methodTwo
. So this will invoke the method in the super class (Base
) namedmethodTwo
. This method prints the letter "B" and then returns. Next the execution returns from the call to thesuper.methodTwo
and prints the letter "D". We return to theBase
classmethodOne
and return from that to theDerived
classmethodOne
and print the letter "C". - AB
- This would be true if the object was created of type
Base
. But the object is really aDerived
object. So all methods are looked for starting with theDerived
class. - ABCD
- After the call to
methodOne
in the super class printing "A", the code continues with the implicitthis.methodTwo
which resolves from the current object's class which isDerived
. Next,methodTwo
in theDerived
class is executed which then callssuper.methodTwo
which invokesprintln
"B" frommethodTwo
in theBase
class. Then the "D" in theDerived
methodTwo
is printed. Finally the program returns tomethodOne
in theDerived
class are prints "C". - ABC
- The call to
methodTwo
insuper.methodOne
is tothis.methodTwo
which is the method from theDerived
class. Consequently the "D" is also printed.
10-11-13: Assume that Base b = new Derived();
appears in a client program. What is the result of the call b.methodOne();
?
public class Base
{
public void methodOne()
{
System.out.print("A");
methodTwo();
}
public void methodTwo()
{
System.out.print("B");
}
}
public class Derived extends Base
{
public void methodOne()
{
super.methodOne();
System.out.print("C");
}
public void methodTwo()
{
super.methodTwo();
System.out.print("D");
}
}
- II only
Point2D
does have a constructor that takes anx
andy
value so this is okay. Also the call to super is the first line of code in the child constructor as required. However, both I and III are okay as well.- III only
- The
x
andy
values inPoint2D
are public and so can be directly accessed by all classes including subclasses. Also there is a no-arg constructor inPoint2D
so the super no-arg constructor will be called before the first line of code in this constructor. - I, II, and III
- I is true because
Point2D
does have a no-arg constructor. II is true becausePoint2D
does have a constructor that takesx
andy
. III is true becausePoint2D
does have a no-arg constructor which will be called before the first line of code is executed in this constructor. The fieldsx
andy
are public inPoint2D
and thus can be directly accessed by all classes. - I and II only
- This would be true if
x
andy
were private inPoint2D
, but they are public. - I only
Point2D
does have a no-arg constructor and since the constructor inPoint3D
doesn't have an explicit call to super as the first line of code in the constructor one will be added for the no-arg constructor. However, both II and III are okay as well.
10-11-14: If you have the following classes. Which of the following constructors would be valid for Point3D
?
public class Point2D {
public int x;
public int y;
public Point2D() {}
public Point2D(int x,int y) {
this.x = x;
this.y = y;
}
// other methods
}
public class Point3D extends Point2D
{
public int z;
// other code
}
I. public Point3D() {}
II. public Point3D(int x, int y, int z)
{
super(x,y);
this.z = z;
}
III. public Point3D(int x, int y)
{
this.x = x;
this.y = y;
this.z = 0;
}