Programmer I Chapter 8: Class Design Flashcards
What does this print?
public class Flamingo { private String color; public void setColor(String color) { color = color; } public static void main(String... unused) { Flamingo f = new Flamingo(); f.setColor("PINK"); System.out.println(f.color); } }
null
Java uses the most granular scope, so when it sees color = color, it thinks you are assigning the method parameter value to itself. The assignment completes successfully within the method, but the value of the instance variable color is never modified and is null when printed in the main()method.
What does this print?
1: public class Duck {
2: private String color;
3: private int height;
4: private int length;
5:
6: public void setData(int length, int theHeight) {
7: length = this.length;
8: height = theHeight;
9: this.color = “white”;
10: }
11:
12: public static void main(String[] args) {
13: Duck b = new Duck();
14: b.setData(1,2);
15: System.out.print(b.length + “ “ + b.height + “ “ +b.color);
16: } }
0 2 white
Line 7 is incorrect, and you should watch for it on the exam. The instance variable length starts out with a 0 value. That 0 is assigned to the method parameter length. The instance variable stays at 0. Line 8 is more straightforward. The parameter the Height and instance variable height have different names. Since there is no naming collision, this is not required. Finally, line 9 shows that a variable assignment is allowed to use this even when there is no duplication of variable names.
What does this print?
1: public class ZooTickets {
2: private String name = “BestZoo”;
3: { System.out.print(name+”-“); }
4: private static int COUNT = 0;
5: static { System.out.print(COUNT+”-“); }
6: static { COUNT += 10; System.out.print(COUNT+”-“); }
7:
8: public ZooTickets() {
9: System.out.print(“z-“);
10: }
11:
12: public static void main(String… patrons) {
13: new ZooTickets();
14: }
15: }
0-10-BestZoo-z-
First, we have to initialize the class. Since there is no super class declared, which means the superclass is Object, we can start with the static components of ZooTickets. In this case, lines 4, 5, and 6 are executed, printing 0- and 10-. Next, we initialize the instance. Again,since there is no superclass declared, we start with the instance components. Lines 2 and 3 are executed, which prints BestZoo-. Finally, we run the constructor on lines 8–10, which outputs z-.
What does this print?
class Primate { public Primate() { System.out.print("Primate-"); } } class Ape extends Primate { public Ape(int fur) { System.out.print("Ape1-"); } public Ape() { System.out.print("Ape2-"); } } public class Chimpanzee extends Ape { public Chimpanzee() { super(2); System.out.print("Chimpanzee-"); } public static void main(String[] args) { new Chimpanzee(); } }
Primate-Ape1-Chimpanzee-
What does this print?
1: public class Cuttlefish {
2: private String name = “swimmy”;
3: { System.out.println(name); }
4: private static int COUNT = 0;
5: static { System.out.println(COUNT); }
6: { COUNT++; System.out.println(COUNT); }
7:
8: public Cuttlefish() {
9: System.out.println(“Constructor”);
10: }
11:
12: public static void main(String[] args) {
13: System.out.println(“Ready”);
14: new Cuttlefish();
15: }
16: }
0 Ready swimmy 1 Constructor
What does this print?
1: class GiraffeFamily {
2: static { System.out.print(“A”); }
3: { System.out.print(“B”); }
4:
5: public GiraffeFamily(String name) {
6: this(1);
7: System.out.print(“C”);
8: }
9:
10: public GiraffeFamily() {
11: System.out.print(“D”);
12: }
13:
14: public GiraffeFamily(int stripes) {
15: System.out.print(“E”);
16: }
17: }
18: public class Okapi extends GiraffeFamily {
19: static { System.out.print(“F”); }
20:
21: public Okapi(int stripes) {
22: super(“sugar”);
23: System.out.print(“G”);
24: }
25: { System.out.print(“H”); }
26:
27: public static void main(String[] grass) {
28: new Okapi(1);
29: System.out.println();
30: new Okapi(2);
31: }
32: }
AFBECHG
BECHG
Start with initializing the Okapi class. Since it has a superclass GiraffeFamily, initialize it first, printing A on line 2. Next,initialize the Okapi class, printing F on line 19.
After the classes are initialized, execute the main() method on line 27.The first line of the main() method creates a new Okapi object,triggering the instance initialization process. Per the first rule, the superclass instance of GiraffeFamily is initialized first. Per our third rule, the instance initializer in the superclass GiraffeFamily is called,and B is printed on line 3. Per the fourth rule, we initialize the constructors. In this case, this involves calling the constructor on line5, which in turn calls the overloaded constructor on line 14. The result is that EC is printed, as the constructor bodies are unwound in the reverse order that they were called
The process then continues with the initialization of the Okapi instance itself. Per the third and fourth rules, H is printed on line 25, and G is printed on line 23, respectively. The process is a lot simpler when you don’t have to call any overloaded constructors. Line 29 then inserts a line break in the output. Finally, line 30 initializes a new Okapi object.The order and initialization are the same as line 28, sans the class initialization, so BECHG is printed again. Notice that D is never printed,as only two of the three constructors in the superclass GiraffeFamily are called.
What does this print?
class Carnivore { protected boolean hasFur = false; }
public class Meerkat extends Carnivore { protected boolean hasFur = true; public static void main(String[] args) { Meerkat m = new Meerkat(); Carnivore c = m; System.out.println(m.hasFur); System.out.println(c.hasFur); } }
true
false
Both of these classes define a hasFur variable, but with different values. Even though there is only one object created by the main() method, both variables exist independently of each other. The output changes depending on the reference variable used.
Which code can be inserted to have the code print 2?
public class BirdSeed { private int numberBags; boolean call; public BirdSeed() { // LINE 1 call = false; // LINE 2 } public BirdSeed(int numberBags) { this.numberBags = numberBags; } public static void main(String[] args) { BirdSeed seed = new BirdSeed(); System.out.print(seed.numberBags); } }
A. Replace line 1 with BirdSeed(2); B. Replace line 2 with BirdSeed(2); C. Replace line 1 with new BirdSeed(2); D. Replace line 2 with new BirdSeed(2); E. Replace line 1 with this(2); F. Replace line 2 with this(2); G. The code prints 2 without any changes
E.
Options A and B will not compile because constructors cannot be called without new. Options C and D will compile but will create a new object rather than setting the fields in this one. The result is the program will print 0, not 2, at runtime. Calling an overloaded constructor, using this(), or a parent constructor, using super(),is only allowed on the first line of the constructor, making option E correct and option F incorrect. Finally, option G is incorrect because the program prints 0 without any changes, not 2.
Which of the following statements about methods are true?(Choose all that apply.)
A. Overloaded methods must have the same signature.
B. Overridden methods must have the same signature.
C. Hidden methods must have the same signature.
D. Overloaded methods must have the same return type.
E. Overridden methods must have the same return type.
F. Hidden methods must have the same return type.
B, C.
Overloaded methods have the method name but a different signature (the method parameters differ), making option A incorrect. Overridden instance methods and hidden static methods must have the same signature (the name and method parameters must match), making options B and C correct.Overloaded methods can have different return types, while overridden and hidden methods can have covariant return types.None of these methods are required to use the same return type,making options D, E, and F incorrect
What is the output of the following program?
1: class Mammal {
2: private void sneeze() {}
3: public Mammal(int age) {
4: System.out.print(“Mammal”);
5: } }
6: public class Platypus extends Mammal {
7: int sneeze() { return 1; }
8: public Platypus() {
9: System.out.print(“Platypus”);
10: }
11: public static void main(String[] args) {
12: new Mammal(5);
13: } }
A. Platypus
B. Mammal
C. PlatypusMammal
D. MammalPlatypus
E. The code will compile if line 7 is changed.
F. The code will compile if line 9 is changed.
F. The code will not compile as is, because the parent class Mammal does not define a no-argument constructor. For this reason, the first line of a Platypus constructor should be an explicit call to super(int), making option F the correct answer. Option E is incorrect, as line 7 compiles without issue. The sneeze() method in the Mammal class is marked private, meaning it is not inherited and therefore is not overridden in the Platypus class. For this reason, the sneeze() method in the Platypus class is free to define the same method with any return type.
Which of the following complete the constructor so that this code prints out 50? (Choose all that apply.)
class Speedster { int numSpots; } public class Cheetah extends Speedster { int numSpots; public Cheetah(int numSpots) { // INSERT CODE HERE } public static void main(String[] args) { Speedster s = new Cheetah(50); System.out.print(s.numSpots); }}
A. numSpots = numSpots; B. numSpots = this.numSpots; C. this.numSpots = numSpots; D. numSpots = super.numSpots; E. super.numSpots = numSpots; F. The code does not compile, regardless of the code inserted into the constructor. G. None of the above
E. The code compiles, making option F incorrect. An instance variable with the same name as an inherited instance variable is hidden, not overridden. This means that both variables exist, and the one that is used depends on the location and reference type. Because the main() method uses a reference type of Speedster to access the num Spots variable, the variable in the Speedster class, not the Cheetah class, must be set to 50. Option A is incorrect, as it reassigns the method parameter to itself. Option B is incorrect, as it assigns the method parameter the value of the instance variable in Cheetah, which is 0. Option C is incorrect, as it assigns the value to the instance variable in Cheetah, not Speedster. Option D is incorrect, as it assigns the method parameter the value of the instance variable in Speedster, which is 0. Options A, B, C, and D all print 0 at runtime. Option E is the only correct answer, as it assigns the instance variable numSpots in the Speedster class a value of 50. The numSpots variable in the Speedster class is then correctly referenced in the main() method, printing 50 at runtime.
What is the output of the following code?
1: class Arthropod {
2: protected void printName(long input) {
3: System.out.print(“Arthropod”);
4: }
5: void printName(int input) {
6: System.out.print(“Spooky”);
7: } }
8: public class Spider extends Arthropod {
9: protected void printName(int input) {
10: System.out.print(“Spider”);
11: }
12: public static void main(String[] args) {
13: Arthropod a = new Spider();
14: a.printName((short)4);
15: a.printName(4);
16: a.printName(5L);
17: } }
A. SpiderSpiderArthropod
B. SpiderSpiderSpider
C. SpiderSpookyArthropod
D. SpookySpiderArthropod
E. The code will not compile because of line 5.
F. The code will not compile because of line 9.
G. None of the above
A. The code compiles and runs without issue, so options E and Fare incorrect. The Arthropod class defines two overloaded versions of the printName() method. The printName() method that takes anint value on line 5 is correctly overridden in the Spider class online 9. Remember, an overridden method can have a broader access modifier, and protected access is broader than package-private access. Because of polymorphism, the overridden method replaces the method on all calls, even if an Arthropod reference variable is used, as is done in the main() method. For these reasons, the overridden method is called on lines 15 and 16,printing Spider twice. Note that the short value is automatically cast to the larger type of int, which then uses the overriddenmethod. Line 17 calls the overloaded method in the Arthropod class, as the long value 5L does not match the overridden method,resulting in Arthropod being printed. Therefore, option A is the correct answer
Which of the following statements about overridden methods are true? (Choose all that apply.)
A. An overridden method must contain method parameters that are the same or covariant with the method parameters in the inherited method.
B. An overridden method may declare a new exception, provided it is not checked.
C. An overridden method must be more accessible than the method in the parent class.
D. An overridden method may declare a broader checked exception than the method in the parent class.
E. If an inherited method returns void, then the overridden version of the method must return void.
F. None of the above
B, E.
The signature must match exactly, making option A incorrect. There is no such thing as a covariant signature. An overridden method must not declare any new checked exceptions or a checked exception that is broader than the inherited method.For this reason, option B is correct, and option D is incorrect.Option C is incorrect because an overridden method may have the same access modifier as the version in the parent class. Finally, overridden methods must have covariant return types, and only void is covariant with void, making option E correct.
Which of the following pairs, when inserted into the blanks, allow the code to compile? (Choose all that apply.)
1: public class Howler {
2: public Howler(long shadow) {
3: _____________;
4: }
5: private Howler(int moon) {
6: super();
7: }
8: }
9: class Wolf extends Howler {
10: protected Wolf(String stars) {
11: super(2L);
12: }
13: public Wolf() {
14: _____________;
15: }
16: }
A. this(3) at line 3, this(“”) at line 14
B. this() at line 3, super(1) at line 14
C. this((short)1) at line 3, this(null) at line 14
D. super() at line 3, super() at line 14
E. this(2L) at line 3, super((short)2) at line 14
F. this(5) at line 3, super(null) at line 14
G. Remove lines 3 and 14
A, C. Option A is correct, as this(3) calls the constructor declared on line 5, while this("") calls the constructor declared on line 10.Option B does not compile, as inserting this() at line 3 results in a compiler error, since there is no matching constructor. Option C is correct, as short can be implicitly cast to int, resulting in this((short)1) calling the constructor declared on line 5. In addition, this(null) calls the String constructor declared on line10. Option D does not compile because inserting super() on line14 results in an invalid constructor call. The Howler class does not contain a no-argument constructor. Option E is also incorrect.Inserting this(2L) at line 3 results in a recursive constructor definition. The compiler detects this and reports an error. Option F is incorrect, as using super(null) on line 14 does not match any parent constructors. If an explicit cast was used, such as super((Integer)null), then the code would have compiled but would throw an exception at runtime during unboxing. Finally,option G is incorrect because the superclass Howler does not contain a no-argument constructor. Therefore, the constructor declared on line 13 will not compile without an explicit call to an overloaded or parent constructor
What is the result of the following?
1: public class PolarBear {
2: StringBuilder value = new StringBuilder(“t”);
3: { value.append(“a”); }
4: { value.append(“c”); }
5: private PolarBear() {
6: value.append(“b”);
7: }
8: public PolarBear(String s) {
9: this();
10: value.append(s);
11: }
12: public PolarBear(CharSequence p) {
13: value.append(p);
14: }
15: public static void main(String[] args) {
16: Object bear = new PolarBear();
17: bear = new PolarBear(“f”);
18: System.out.println(((PolarBear)bear).value);
19: } }
A. tacb B. tacf C. tacbf D. tcafb E. taftacb F. The code does not compile. G. An exception is thrown
C.
The code compiles and runs without issue, making options F and G incorrect. Line 16 initializes a PolarBear instance and assigns it to the bear reference. The variable declaration and instance initializers are run first, setting value to tac. The constructor declared on line 5 is called, resulting in value being set to tacb. Remember, a static main() method can access private constructors declared in the same class. Line 17 creates another PolarBear instance, replacing the bear reference declared on line 16. First, value is initialized to tac as before. Line 17 callsthe constructor declared on line 8, since String is the narrowest match of a String literal. This constructor then calls the overloaded constructor declared on line 5, resulting in value being updated to tacb. Control returns to the previous constructor, with line 10 updating value to tacbf, and making option C the correct answer. Note that if the constructor declared on line 8 did not exist, then the constructor on line 12 would match. Finally, the bear reference is properly cast to PolarBear on line 18, making the value parameter accessible