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
Which of the following method signatures are valid overrides of the hairy() method in the Alpaca class? (Choose all that apply.)
import java.util.*; public class Alpaca { protected List < String > hairy(int p) { return null; }}
A. List < String > hairy(int p) { return null; }
B. public List < String > hairy(int p) { return null; }
C. public List < CharSequence > hairy(int p) { return null; }
D. private List < String > hairy(int p) { return null; }
E. public Object hairy(int p) { return null; }
F. public ArrayList < String > hairy(int p) { return null; }
G. None of the above
B, F.
A valid override of a method with generic arguments musthave a return type that is covariant, with matching generic typeparameters. Option B is correct, as it is just restating the originalreturn type. Option F is also correct, as ArrayList is a subtype ofList. The rest of the method declarations do not compile. OptionsA and D are invalid because the access levels, package-private andprivate, are more restrictive than the inherited access modifier,protected. Option C is incorrect because while CharSquence is asubtype of String, the generic type parameters must matchexactly. Finally, option E is incorrect as Object is a supertype ofList and therefore not covariant
How many lines of the following program contain a compilation error?
1: public class Rodent {
2: public Rodent(var x) {}
3: protected static Integer chew() throws Exception {
4: System.out.println(“Rodent is chewing”);
5: return 1;
6: }
7: }
8: class Beaver extends Rodent {
9: public Number chew() throws RuntimeException {
10: System.out.println(“Beaver is chewing on wood”);
11: return 2;
12: } }
A. None B. 1 C. 2 D. 3 E. 4 F. 5
D.
The code doesn’t compile, so option A is incorrect. The first compilation error is on line 2, as var cannot be used as a constructor argument type. The second compilation error is online 8. Since Rodent declares at least one constructor and it is not a no-argument constructor, Beaver must declare a constructor with an explicit call to a super() constructor. Line 9 contains two compilation errors. First, the return types are not covariant since Number is a supertype, not a subtype, of Integer. Second, the inherited method is static, but the overridden method is not,making this an invalid override. The code contains four compilation errors, although they are limited to three lines,making option D the correct answer
Which of the following statements about polymorphism are true?(Choose all that apply.)
A. An object may be cast to a subtype without an explicit cast. B. If the type of a method argument is an interface, then a reference variable that implements the interface may be passed to the method. C. A method that takes a parameter with type java.lang.Object can be passed any variable. D. All cast exceptions can be detected at compile-time. E. By defining a final instance method in the superclass, you guarantee that the specific method will be called in the parent class at runtime. F. Polymorphism applies only to classes, not interfaces
B, C, E. An object may be cast to a supertype without an explicitcast but requires an explicit cast to be cast to a subtype, makingoption A incorrect. Option B is correct, as an interface methodargument may take any reference type that implements theinterface. Option C is also correct, as a method that acceptsjava.lang.Object can accept any variable since all objects inheritjava.lang.Object. This also includes primitives, which can beautoboxed to their wrapper classes. Some cast exceptions can bedetected as errors at compile-time, but others can only bedetected at runtime, so option D is incorrect. Due to the nature ofpolymorphism, a final instance method cannot be overridden ina subclass, so calls in the parent class will not be replaced, makingoption E correct. Finally, polymorphism applies to classes and interfaces alike, making option F incorrect.
Which of the following statements can be inserted in the blank so that the code will compile successfully? (Choose all that apply.)
public class Snake {} public class Cobra extends Snake {} public class GardenSnake extends Cobra {} public class SnakeHandler { private Snake snake; public void setSnake(Snake snake) { this.snake = snake; } public static void main(String[] args) { new SnakeHandler().setSnake(\_\_\_\_\_\_\_\_\_\_\_); }}
A. new Cobra() B. new Snake() C. new Object() D. new String("Snake") E. new GardenSnake() F. null G. None of the above. The class does not compile, regardless of the value inserted in the blank
A, B, E, F. The code compiles if the correct type is inserted in theblank, so option G is incorrect. The setSnake() method requiresan instance of Snake or any subtype of Snake. The Cobra class is asubclass of Snake, so it is a subtype. The GardenSnake class is asubclass of Cobra, which, in turn, is a subclass of Snake, alsomaking GardenSnake a subtype of Snake. For these reasons, optionsA, B, and E are correct. Option C is incorrect because Object is asupertype of Snake, not a subtype, as all instances inherit Object.Option D is incorrect as String is an unrelated class and does notinherit Snake. Finally, a null value can always be passed as anobject value, regardless of type, so option F is correct
Which of these classes compile and will include a default constructor created by the compiler? (Choose all that apply.)
A. public class Bird {} B. public class Bird {public bird() {}} C. public class Bird {public bird(String name) {}} D. public class Bird {public Bird() {}} E. public class Bird {Bird(String name) {}} F. public class Bird {private Bird(int age) {}} G. public class Bird {public Bird bird() {return null;}}
A, G. The compiler will insert a default no-argument constructor ifthe class compiles and does not define any constructors. OptionsA and G fulfill this requirement, making them the correctanswers. The bird() declaration in option G is a methoddeclaration, not a constructor. Options B and C do not compile.Since the constructor name does not match the class name, thecompiler treats these as methods with missing return types.Options D, E, and F all compile, but since they declare at least oneconstructor, the compiler does not supply one
Which of the following statements about inheritance are correct?(Choose all that apply.)
A. A class can directly extend any number of classes. B. A class can implement any number of interfaces. C. All variables inherit java.lang.Object. D. If class A is extended by B, then B is a superclass of A. E. If class C implements interface D, then C is subtype of D. F. Multiple inheritance is the property of a class to have multiple direct superclasses
B, E, F. A class can only directly extend a single class, making option A incorrect. A class can implement any number of interfaces, though, making option B correct. Option C is incorrect because primitive types do not inherit java.lang.Object. If a class extends another class, then it is a subclass, not a superclass,making option D incorrect. A class that implements an interface is a subtype of that interface, making option E correct. Finally,option F is correct as it is an accurate description of multiple inheritance, which is not permitted in Java
What is the result of the following?
1: class Arachnid {
2: static StringBuilder sb = new StringBuilder();
3: { sb.append(“c”); }
4: static
5: { sb.append(“u”); }
6: { sb.append(“r”); }
7: }
8: public class Scorpion extends Arachnid {
9: static
10: { sb.append(“q”); }
11: { sb.append(“m”); }
12: public static void main(String[] args) {
13: System.out.print(Scorpion.sb + “ “);
14: System.out.print(Scorpion.sb + “ “);
15: new Arachnid();16: new Scorpion();
17: System.out.print(Scorpion.sb);
18: } }
A. qu qu qumrcrc B. u u ucrcrm C. uq uq uqmcrcr D. uq uq uqcrcrm E. qu qu qumcrcr F. qu qu qucrcrm G. The code does not compile
D. The code compiles, so option G is incorrect. Based on order of initialization, the static components are initialized first, starting with the Arachnid class, since it is the parent of the Scorpion class,which initializes the StringBuilder to u. The static initializer in Scorpion then updates sb to contain uq, which is printed twice by lines 13 and 14 along with spaces separating the values. Next, an instance of Arachnid is initialized on line 15. There are two instance initializers in Arachnid, and they run in order, appending cr to the StringBuilder, resulting in a value of uqcr. An instance of Scorpion is then initialized on line 16. The instance initializers in the superclass Arachnid run first, appending cr again and updating the value of sb to uqcrcr. Finally, the instance initializer in Scorpion runs and appends m. The program completes with the final value printed being uq uq uqcrcrm, making option D the correct answer
Which of the following methods are valid overrides of the friendly() method in the Llama class? (Choose all that apply.)
import java.util.*; public class Llama { void friendly(List < String > laugh, Iterable < Short > s) {} }
A. void friendly(List < CharSequence > laugh, Iterable < Short > s) {}
B. void friendly(List < String > laugh, Iterable < Short > s) {}
C. void friendly(ArrayList < String > laugh, Iterable < Short > s) {}
D. void friendly(List < String > laugh, Iterable < Integer > s){}
E. void friendly(ArrayList < CharSequence > laugh, Object s){}
F. void friendly(ArrayList < String > laugh, Iterable… s) {}
G. None of the above
B. A valid override of a method with generic arguments must have the same signature with the same generic types. For this reason,only option B is correct. Because of type erasure, the generic type parameter will be removed when the code is compiled. Therefore,the compiler requires that the types match. Options A and D donot compile for this reason. Options C, E, and F do compile, but since the generic class changed, they are overloads, not overrides.Remember, covariant types only apply to return values ofoverridden methods, not method parameters
Which of the following statements about inheritance andvariables are true? (Choose all that apply.)
A. Instance variables can be overridden in a subclass. B. If an instance variable is declared with the same name as aninherited variable, then the type of the variable must becovariant. C. If an instance variable is declared with the same name as aninherited variable, then the access modifier must be at leastas accessible as the variable in the parent class. D. If a variable is declared with the same name as an inheritedstatic variable, then it must also be marked static. E. The variable in the child class may not throw a checkedexception that is new or broader than the class of anyexception thrown in the parent class variable. F. None of the above
F. Options A–E are incorrect statements about inheritance and variables, making option F the correct answer. Option A is incorrect because variables can only be hidden, not overridden via inheritance. This means that they are still accessible in the parentclass and do not replace the variable everywhere, as overridingdoes. Options B, C, and E are also incorrect as they more closelymatch rules for overriding methods. Also, option E is invalid asvariables do not throw exceptions. Finally, option D is incorrect asthis is a rule for hiding static methods.