Programmer I Chapter 8: Class Design Flashcards

1
Q

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);
   }
}
A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

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: } }

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

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: }

A

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-.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

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();
   }
}
A

Primate-Ape1-Chimpanzee-

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

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: }

A
0
Ready
swimmy
1
Constructor
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

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: }

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

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);
   }
}
A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

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
A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

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.

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

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.

A
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.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

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
A
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.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

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
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
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

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

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

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
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
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

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
A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

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

A

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

17
Q

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
A

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

18
Q

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
A
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.
19
Q

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
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
20
Q

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
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
21
Q

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
A
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
22
Q

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
A
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
23
Q

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

A
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
24
Q

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
A
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.
25
Q

Which of the following are true? (Choose all that apply.)

A. this() can be called from anywhere in a constructor.
B. this() can be called from anywhere in an instance method.
C. this.variableName can be called from any instance method in the class.
D. this.variableName can be called from any static method in the class.
E. You can call the default constructor written by the compiler using this().
F. You can access a private constructor with the main() method in the same class.

A
C, F. 
Calling an overloaded constructor with this() may be used only as the first line of a constructor, making options A and B incorrect. Accessing this.variableName can be performed from any instance method, constructor, or instance initializer, but not from a static method or static initializer. For this reason, option C is correct, and option D is incorrect. Option E is tricky. The default constructor is written by the compiler only if no user-defined constructors were provided. And this() can only be called from a constructor in the same class. Since there can be no user-defined constructors in the class if a default constructor was created, it is impossible for option E to be true. Since the main()method is in the same class, it can call private methods in the class, making option F correct
26
Q

Which statements about the following classes are correct?(Choose all that apply.)

1: public class Mammal {
2: private void eat() {}
3: protected static void drink() {}
4: public Integer dance(String p) { return null; }
5: }
6: class Primate extends Mammal {
7: public void eat(String p) {}
8: }
9: class Monkey extends Primate {
10: public static void drink() throws RuntimeException{}
11: public Number dance(CharSequence p) { return null; }
12: public int eat(String p) {}
13: }

A. The eat() method in Mammal is correctly overridden on line 7.
B. The eat() method in Mammal is correctly overloaded on line 7.
C. The drink() method in Mammal is correctly hidden on line 10.
D. The drink() method in Mammal is correctly overridden on line10.
E. The dance() method in Mammal is correctly overridden on line11.
F. The dance() method in Mammal is correctly overloaded on line11.
G. The eat() method in Primate is correctly hidden on line 12.
H. The eat() method in Primate is correctly overloaded on line12

A
C, F. 
The eat() method is private in the Mammal class. Since it is not inherited in the Primate class, it is neither overridden nor overloaded, making options A and B incorrect. The drink()method in Mammal is correctly hidden in the Monkey class, as thesignature is the same, making option C correct and option Dincorrect. The version in the Monkey class throws a new exception,but it is unchecked; therefore, it is allowed. The dance() methodin Mammal is correctly overloaded in the Monkey class because thesignatures are not the same, making option E incorrect and optionF correct. For methods to be overridden, the signatures mustmatch exactly. Finally, line 12 is an invalid override and does notcompile, as int is not covariant with void, making options G andH both incorrect
27
Q

What is the output of the following code?

1: class Reptile {
2: {System.out.print(“A”);}
3: public Reptile(int hatch) {}
4: void layEggs() {
5: System.out.print(“Reptile”);
6: } }
7: public class Lizard extends Reptile {
8: static {System.out.print(“B”);}
9: public Lizard(int hatch) {}
10: public final void layEggs() {
11: System.out.print(“Lizard”);
12: }
13: public static void main(String[] args) {
14: Reptile reptile = new Lizard(1);
15: reptile.layEggs();
16: } }

A. AALizard
B. BALizard
C. BLizardA
D. ALizard
E. The code will not compile because of line 10.
F. None of the above
A
F. 
The Reptile class defines a constructor, but it is not a no-argument constructor. Therefore, the Lizard constructor must explicitly call super(), passing in an int value. For this reason,line 9 does not compile, and option F is the correct answer. If the Lizard class were corrected to call the appropriate super()constructor, then the program would print BALizard at runtime,with the static initializer running first, followed by the instance initializer, and finally the method call using the overriddenmethod
28
Q

Which statement about the following program is correct?

1: class Bird {
2: int feathers = 0;
3: Bird(int x) { this.feathers = x; }
4: Bird fly() {
5: return new Bird(1);
6: } }
7: class Parrot extends Bird {
8: protected Parrot(int y) { super(y); }
9: protected Parrot fly() {
10: return new Parrot(2);
11: } }
12: public class Macaw extends Parrot {
13: public Macaw(int z) { super(z); }
14: public Macaw fly() {
15: return new Macaw(3);
16: }
17: public static void main(String… sing) {
18: Bird p = new Macaw(4);
19: System.out.print(((Parrot)p.fly()).feathers);
20: } }

A. One line contains a compiler error.
B. Two lines contain compiler errors.
C. Three lines contain compiler errors.
D. The code compiles but throws a ClassCastException at runtime.
E. The program compiles and prints 3.
F. The program compiles and prints 0.
A
E. 
The program compiles and runs without issue, making options A through D incorrect. The fly() method is correctly overridden in each subclass since the signature is the same, the access modifier is less restrictive, and the return types are covariant. For covariance, Macaw is a subtype of Parrot, which is a subtype o fBird, so overridden return types are valid. Likewise, the constructors are all implemented properly, with explicit calls to the parent constructors as needed. Line 19 calls the overridden version of fly() defined in the Macaw class, as overriding replaces the method regardless of the reference type. This results in feathers being assigned a value of 3. The Macaw object is then cast to Parrot, which is allowed because Macaw inherits Parrot. The feathers variable is visible since it is defined in the Bird class, and line 19 prints 3, making option E the correct answer
29
Q

What does the following program print?

1: class Person {
2: static String name;
3: void setName(String q) { name = q; } }
4: public class Child extends Person {
5: static String name;
6: void setName(String w) { name = w; }
7: public static void main(String[] p) {
8: final Child m = new Child();
9: final Person t = m;
10: m.name = “Elysia”;
11: t.name = “Sophia”;
12: m.setName(“Webby”);
13: t.setName(“Olivia”);
14: System.out.println(m.name + “ “ + t.name);
15: } }

A. Elysia Sophia
B. Webby Olivia
C. Olivia Olivia
D. Olivia Sophia
E. The code does not compile.
F. None of the above
A
D. 
The code compiles and runs without issue, making option Eincorrect. The Child class overrides the setName() method andhides the static name variable defined in the inherited Personclass. Since variables are only hidden, not overridden, there aretwo distinct name variables accessible, depending on the locationand reference type. Line 8 creates a Child instance, which isimplicitly cast to a Person reference type on line 9. Line 10 usesthe Child reference type, updating Child.name to Elysia. Line 11uses the Person reference type, updating Person.name to Sophia.Lines 12 and 13 both call the overridden setName() instancemethod declared on line 6. This sets Child.name to Webby on line 12and then to Olivia on line 13. The final values of Child.name andPerson.name are Olivia and Sophia, respectively, making option Dthe correct answer
30
Q

What is the output of the following program?

1: class Canine {
2: public Canine(boolean t) { logger.append(“a”); }
3: public Canine() { logger.append(“q”); }
4:
5: private StringBuilder logger = new StringBuilder();
6: protected void print(String v) { logger.append(v); }
7: protected String view() { return logger.toString(); }
8: }
9:
10: class Fox extends Canine {
11: public Fox(long x) { print(“p”); }
12: public Fox(String name) {
13: this(2);
14: print(“z”);
15: }
16: }
17:
18: public class Fennec extends Fox {
19: public Fennec(int e) {
20: super(“tails”);
21: print(“j”);
22: }
23: public Fennec(short f) {
24: super(“eevee”);
25: print(“m”);
26: }
27:
28: public static void main(String… unused) {
29: System.out.println(new Fennec(1).view());
30: } }

A. qpz
B. qpzj
C. jzpa
D. apj
E. apjm
F. The code does not compile.
G. None of the above
A
B. 
The program compiles, making option F incorrect. The constructors are called from the child class upward, but since each line of a constructor is a call to another constructor, via this() orsuper(), they are ultimately executed in top-down manner. Online 29, the main() method calls the Fennec() constructor declaredon line 19. Remember, integer literals in Java are considered intby default. This constructor calls the Fox() constructor defined online 12, which in turn calls the overloaded Fox() constructordeclared on line 11. Since the constructor on line 11 does notexplicitly call a parent constructor, the compiler inserts a call tothe no-argument super() constructor, which exists on line 3 of theCanine class. Since Canine does not extend any classes, thecompiler will also insert a call to the no-argument super()constructor defined in java.lang.Object, although this has littleimpact on the output. Line 3 is then executed, adding q to theoutput, and the compiler chain is unwound. Line 11 then executes,adding p, followed by line 14, adding z. Finally, line 21 is executed,
and j is added, resulting in a final value for logger of qpzj, andmaking option B correct. For the exam, remember to followconstructors from the lowest level upward to determine thecorrect pathway, but then execute them from the top down usingthe established order
31
Q

Which statements about polymorphism and method inheritance are correct? (Choose all that apply.)

A. It cannot be determined until runtime which overridden method will be executed in a parent class.
B. It cannot be determined until runtime which hidden method will be executed in a parent class.
C. Marking a method static prevents it from being overridden or hidden.
D. Marking a method final prevents it from being overridden or hidden.
E. The reference type of the variable determines which overridden method will be called at runtime.
F. The reference type of the variable determines which hidden method will be called at runtime.

A

A, D, F.
Polymorphism is the property of an object to take on many forms. Part of polymorphism is that methods are replaced through overriding wherever they are called, regardless ofwhether they’re in a parent or child class. For this reason, optionA is correct, and option E incorrect. With hidden static methods,Java relies on the location and reference type to determine whichmethod is called, making option B incorrect and F correct. Finally,making a method final, not static, prevents it from beingoverridden, making option D correct and option C incorrect

32
Q

What is printed by the following program?

1: class Antelope {
2: public Antelope(int p) {
3: System.out.print(“4”);
4: }
5: { System.out.print(“2”); }
6: static { System.out.print(“1”); }
7: }
8: public class Gazelle extends Antelope {
9: public Gazelle(int p) {
10: super(6);
11: System.out.print(“3”);
12: }
13: public static void main(String hopping[]) {
14: new Gazelle(0);
15: }
16: static { System.out.print(“8”); }
17: { System.out.print(“9”); }
18: }

A. 182640
B. 182943
C. 182493
D. 421389
E. The code does not compile.
F. The output cannot be determined until runtime.
A
C. 
The code compiles and runs without issue, making options E and F incorrect. First, the class is initialized, starting with the superclass Antelope and then the subclass Gazelle. This involves invoking the static variable declarations and static initializers.The program first prints 1, followed by 8. Then, we follow the constructor pathway from the object created on line 14 upward,initializing each class instance using a top-down approach. Within each class, the instance initializers are run, followed by the referenced constructors. The Antelope instance is initialized,printing 24, followed by the Gazelle instance, printing 93. The final output is 182493, making option C the correct answer
33
Q

How many lines of the following program contain a compilation error?

1: class Primate {
2: protected int age = 2;
3: { age = 1; }
4: public Primate() {
5: this().age = 3;
6: }
7: }
8: public class Orangutan {
9: protected int age = 4;
10: { age = 5; }
11: public Orangutan() {
12: this().age = 6;
13: }
14: public static void main(String[] bananas) {
15: final Primate x = (Primate)new Orangutan();16: System.out.println(x.age);
17: }
18: }

A. None, and the program prints 1 at runtime.
B. None, and the program prints 3 at runtime.
C. None, but it causes a ClassCastException at runtime.
D. 1
E. 2
F. 3
G. 4

A
F. 
The code does not compile, so options A through C are incorrect. Both lines 5 and 12 do not compile, as this() is used instead of this. Remember, this() refers to calling a constructor, whereas this is a reference to the current instance. Next, the compiler does not allow casting to an unrelated class type. Since Orangutan is not a subclass of Primate, the cast on line 15 is invalid, and the code does not compile. Due to these three lines containing compilation errors, option F is the correct answer.
Note that if Orangutan was made a subclass of Primate and the this() references were changed to this, then the code would compile and print 3 at runtime.