Java OCP Part 2. Design Patterns and Principles

अब Quizwiz के साथ अपने होमवर्क और परीक्षाओं को एस करें!

C. Interfaces allow Java to support multiple inheritance because a class mayimplement any number of interfaces. On the other hand, an anonymous inner classmay implement at most one interface, since it does not have a class definition toimplement any others.

Fill in the blanks: ____________allow Java to support multiple inheritance, and anonymous inner classes can ____________of them. A. Abstract classes, extend at most one B. Abstract classes, extend any number C. Interfaces, implement at most one D. Interfaces, implement any number

5 56. Remember that polymorphism applies only to instance methods, not to static methods and not to static or instance variables.

class Car2 { static int i1 = 5; int i2 = 6; public static void m1() { System.out.print(i1); } } class Mini2 extends Car2 { static int i1 = 7; int i2 = 8; public static void m1() { System.out.print(i1); } public static void main(String[] args) { Car2 c = new Mini2(); c.m1(); System.out.print(" " + c.i1 + c.i2); } } // What is the result?

B. The equals() method shown in the code doesn't properly override Object.equals(), which takes an object. Therefore, when the code adds instances to the set, the default equals method from class Object is used.

class Nearly { String value; Nearly(String v) { value = v; } public int hashCode() { return 1; } public boolean equals(Nearly n) { if(value.charAt(0) == n.value.charAt(0)) return true; return false; } public static void main(String[] sss) { Nearly n1 = new Nearly("aaa"); Nearly n2 = new Nearly("aaa"); String s = "-"; if( n1.equals(n2) ) s += "1"; if( n1 == n2 ) s += "2"; Set<Nearly> set = new HashSet<Nearly>(); set.add(n1); set.add(n2); System.out.println( s + " " + set.size() ); } } // What is the result? A. -1 1 B. -1 2 C. -12 1 D. -12 2 E. Compilation fails F. An exception is thrown at runtime

D. An object is required to have the same value for repeated calls to hashCode() if the value has not changed. This makes III incorrect. If two objects are equal, they are required to have the same hash code. Since equality must be reflexive, it cann't return false if the same object is passed, and I is incorrect. Since equals() must return false when null is passed in, it cannot be true and II is incorrect. Therefore,Option D is the answer.

class Sticker { public int hashCode() { return _____________; } public boolean equals(Object o) { return _____________; } } // Which of the following pairs of values can fill in the blanks to comply with the contract of the hashCode() and equals() methods? a. 1, false b. 1, true c. new Random().nextInt(), false d. No one

A The code compiles without issue and prints 15, making Option A correct and Option D incorrect. The main() method defines a local class Oak that correctly extends Tree, a static nested class, making Option B incorrect. Finally, the method getWater() is permitted to read the variable water, defined in the main() method, since it is effectively final, having a value of 15 when it is defined.

public class Woods { static class Tree {} public static void main(String[] leaves) { int water = 10+5; final class Oak extends Tree { // p1 public int getWater() { return water; // p2 } } System.out.print(new Oak().getWater()); } } // What is the output? A. 15 B. The code does not compile because of line p1 . C. The code does not compile because of line p2 . D. None of the above

D. (rows 8 and 11) This application declares an anonymous inner class that implements the Edible interface. Interface methods are public, whereas the override in the anonymous inner class uses package-private access. Since this reduces the visibility of the method, the declaration of eat() on line 8 does not compile. Next, the declaration of the apple object must end with a semicolon (;) on line 11, and it does not.

3: interface Edible { void eat(); } 4: public class ApplePicking { 5: public static void main(String[] food) { 6: Edible apple = new Edible() { 7: @Override 8: void eat() { 9: System.out.print("Yummy!"); 10: } } } } // What is the output? A. The application completes without printing anything. B. Yummy! C. One line of this application fails to compile. D. Two lines of this application fail to compile.

All three are valid functional interfaces

@FunctionalInterface public interface Sprint { public void sprint(Animal animal); } Assuming the Sprint is our previously defined functional interface, which ones would also be functional interfaces? 1. public interface Run extends Sprint {} 2. public interface SprintFaster extends Sprint { public void sprint(Animal animal); } 3. public interface Skip extends Sprint { public default int getHopCount(Kangaroo kangaroo) {return 10;} public static void skip(int speed) {} }

C,D. C,D is the correct answer since this code contains two compile-time errors. (line 3 is incorrect because the static method but has no method body, chew() on line 4 is also incorrect)

Choose the correct statement about the following code: 1: public interface Herbivore { 2: int amount = 10; 3: public static void eatGrass(); 4: public int chew() { return 13; } } // Choose all that apply A. It compiles and runs without issue. B. The code will not compile because of line 2. C. The code will not compile because of line 3. D. The code will not compile because of line 4.

B. An interface can be extended by another interface and a class can be extended by another class, making the second part of Options A, C, and D incorrect. Option B is correct because an enum cannot be extended. Note that Option C is also incorrect for this reason.

Fill in the blanks: It is possible to extend an ____________but not an ____________. A. interface, abstract class B. abstract class, enum C. enum, interface D. abstract class, interface

A. A calls sorted(), passing a Comparator constructed from two Comparators: byTemp and byMonth. The method thenComparing() is a method on a Comparator that combines two Comparators. The stream is sorted first by byTemp and then by byMonth.

Given class Weather has methods: int getTemp() and int getMonth() and List<Weather> weather = ...; // properly created and populated Comparator<Weather> byTemp= (w1,w2)->w1.getTemp()<w2.getTemp() ? -1 : 1; Comparator<Weather> byMonth= (w1,w2)->w1.getMonth()<w2.getMonth() ? -1 : 1; // L1 Which, when inserted at line L1, enable the code to create stream when run it will sort the weather list by temperature and sort weather entries with the same temperature by month? A. weather.stream().sorted(byTemp.thenComparing(byMonth)); B. weather.stream().sorted(byTemp).thenComparing(byMonth); C. weather.stream().sorted(byTemp).thenComparing.sorted(byMonth); D. weather.stream().sorted().thenComparing(byTemp, byMonth); E. weather.stream().sorted(byTemp, byMonth);

Not compile. opt is an Optional<Double> . This means the Supplier must return a Double . Since this supplier returns an exception, the type does not match.

Optional<Double> opt = Optional.of(1.1); System.out.println( opt.orElse( () -> new IllegalStateException() ) ); // What output ?

ABDEGH In the code, first the implicit calls to super are made. Then, for each constructor, the init block runs, after which the rest of the constructor's statements run.

abstract class Top { { System.out.print("A"); } public Top() { System.out.print("B"); } public Top(String s) { System.out.print("C"); } } class Middle extends Top { { System.out.print("D"); } public Middle() { System.out.print("E"); } public Middle(String s) { System.out.print("F"); } } public class Bottom extends Middle { { System.out.print("G"); } public Bottom() { System.out.print("H"); } public Bottom(String s) { System.out.print("I"); } public static void main(String [] args) { new Bottom(); } } // What is the result?

C. Only instance methods can be overridden, and calls to super only apply to overridden methods.

class AlternateFuel { int getRating() { return 42; } static int getRating2() { return 43; } } class BioDiesel extends AlternateFuel { public static void main(String[] args) { new BioDiesel().go(); System.out.print( super.getRating2() ); // #1 } void go() { System.out.print( super.getRating() ); // #2 } } //What is the result? A. 4243 B. 4342 C. Compilation fails due only to an error on line #1 D. Compilation fails due only to an error on line #2 E. Compilation fails due to errors on both lines #1 and #2 F. An exception is thrown at runtime

b0 r1 r4 h0 h2 pre b1 b2 r3 r2 h1 hawk Static init blocks are executed at class loading time; instance init blocks run right after the call to super() in a constructor. When multiple init blocks of a single type occur in a class, they run in order, from the top down.

class Bird { static { System.out.println("b0"); } { System.out.println("b1"); } public Bird() { System.out.println("b2"); } } class Raptor extends Bird { static { System.out.println("r1"); } public Raptor() { System.out.println("r2"); } { System.out.println("r3"); } static { System.out.println("r4"); } } public class Hawk extends Raptor{ static { System.out.println("h0"); } { System.out.println("h1"); } public static void main(String[] args) { System.out.println("pre"); new Hawk(); System.out.println("hawk"); } static { System.out.println("h2"); } } // What is the result?

D. The code includes a static init block and a normal (instance) init block. The tricky part is that instance init blocks run after the call to super() but before the object's own constructor runs.

class Blocks { Blocks() { System.out.print("b "); } } public class Legos extends Blocks { Legos() { System.out.print("L "); } public static void main(String[] args) { Legos x = new Legos(); } static { System.out.print("si "); } { System.out.print("i "); } } // What is the result? A. si i L B. si L i C. si b L i D. si b i L E. Compilation fails F. An exception is thrown at runtime

B While the cast itself is fine, a Building cannot be stored in a House reference, which means the assignment fails to compile. Option B is correct and is the only line with a compiler error in this code. Note that if the declaration of q was removed, the declaration of p would produce a ClassCastException at runtime.

class Building {} class House extends Building{} // Which not to compile? (Choose all that apply) public void convert() { 1: Building b = new Building(); 2: House h = new House(); 3: Building bh = new House(); A: Building p = (House) b; B: House q = (Building) h; C: Building r = (Building) bh; D: House s = (House) bh; }

A. There are a couple of things to notice. First, it's fine to declare the Comparator as an inner class. Second, the compare() method, as implemented, reverses the natural order using the array element's SECOND character.

class Comp2 { public static void main(String[] args) { String[] words = { "Good", "Bad", "Ugly" }; Comparator<String> best = new Comparator<String>() { public int compare(String s1, String s2) { return s2.charAt(1) - s1.charAt(1); } }; Arrays.sort(words, best); System.out.println(words[0]); } } // What is the result? A. Good B. Bad C. Ugly D. The code does not compile E. An exception is thrown at runtime

C, D. A is incorrect because there is no mechanism in this code to restrict the number of objects that can be created in either class. B is incorrect because method m1 is overloaded, not overridden. E is incorrect because getSB() returns a reference to an object, which would allow the invoking code to change the state of myOO objects.

class OO { void m1() { ; } } class myOO extends OO { private StringBuilder sb = new StringBuilder("mySB"); void m1(int x) { ; } StringBuilder getSB() { return sb; } } Which OO concepts are properly implemented? (Choose all that apply.) A. singleton B. overriding C. overloading D. inheritance E. encapsulation

A. The code does not compile because the declaration of isDanger() in the classSeriousDanger is an invalid method override. An overridden method may not throw a broader checked exception than it inherits. Since Exception is a superclass of Problem,thrown by the inherited method in the Danger class, the override of this checkedexception is invalid.

class Problem extends Exception {} abstract class Danger { protected abstract void isDanger() throws Problem; } public class SeriousDanger extends Danger { protected void isDanger() throws Exception { // m1 throw new RuntimeException(); } public static void main(String[] will) throws Throwable { // m2 new SeriousDanger().isDanger(); // m3 } } // What is the output? A. The code does not compile because of line m1 B. The code does not compile because of line m2 . C. The code does not compile because of line m3 . D. The code compiles but throws an exception at runtime.

A,B,C. The hashCode() method in the Object class does not have a parameter. Therefore,the Sticker class provides an overloaded method rather than an overridden one. Since it is not an overridden method, the contract for the Object class' hashCode() methoddoes not apply, and any int value can be returned. Therefore, Option C is correct.

class Sticker { public int hashCode(Object o) { return_____________ ; } public boolean equals(Object o) { return true; } } // Which of the following values can fill in the blank for the class to be correctly implemented? (Choose all that apply) A. -1 B. 5 C. new Random().nextInt()

B The Hammer class is a subclass of the Tool class. Since the use() method in Hammer is intended to override the one in Tool, there are certain rules. One is that the access modifier must not be more specific. Therefore, trying to make it private is a problem.Option B is correct and r2 is the only line with a compiler error in this code.

class Tool { void use() { } // r1 } class Hammer extends Tool { private void use() { } // r2 public void bang() { } // r3 } // Which is fail to compile? A. r1 B. r2 C. r3 D. None of the above

A. By default, an interface's methods are public so theTablet.doStuff method must be public, too. The rest of the code isvalid

interface Gadget { void doStaff(); } abstract class Electronics { void getPower() { System.out.println("plug in "); } } public class Tablet extends Electronics implements Gadget { void doStaff() { System.out.println(" show book"); } public static void main(String[] args) { new Tablet().getPower(); new Tablet().doStaff(); } } // Which are true? (Choose all that apply.) A. The class Tablet will NOT compile B. The interface Gadget will NOT compile C. The output will be plug in show book D. The abstract class Electronic will NOT compile

B,D, A is incorrect because it fails to compile. B is correct because classes Bird and Parrot are in the same hierarchy tree, so an object of base class Bird can be explicitly casted to its derived class Parrotat compilation. But the JVM can determine the type of the objects at runtime. C is incorrect because class Vulture implements the interface Scavenger,so this code will also execute without the explicit cast. D is correct because an instance of a nonfinal class can be casted to any inter-face type using an explicit cast during the compilation phase. But the exact object types are validated during runtime and a ClassCastException is thrown if theobject's class doesn't implement that interface.

interface Scavenger{} class Bird{} class Parrot extends Bird{} class Vulture extends Bird implements Scavenger{} class BirdSanctuary { public static void main(String args[]) { Bird bird = new Bird(); Parrot parrot = new Parrot(); Vulture vulture = new Vulture(); //L1 } } // In which of the following options will the code, when inserted at //L1, throws a ClassCastException ? A. Vulture vulture2 = (Vulture)parrot; B. Parrot parrot2 = (Parrot)bird; C. Scavenger sc = (Scavenger)vulture; D. Scavenger sc2 = (Scavenger)bird;

A, B, D, and E are correct declarations. C is incorrect because the input can contain any supertype of T (such as Object), and those elements can't be added to an output list of type T. F and G are incorrect because you can't use wildcards in the type variable declaration.

public class BackLister { // L1 List<T> output = new LinkedList<T>(); for (T t : input) output.add(0, t); return output; } } // Which can be inserted at // L1 to compile and run without error? A. public static <T> List<T> backwards(List<T> input) { B. public static <T> List<T> backwards(List<? extends T> input) { C. public static <T> List<T> backwards(List<? super T> input) { D. public static <T> List<? extends T> backwards(List<T> input) { E. public static <T> List<? super T> backwards(List<T> input) { F. public static <? extends T> List<T> backwards(List<T> input) { G. public static <? super T> List<T> backwards(List<T> input) {

C,G. C is the correct syntax to access an inner class's outer instance method from an initialization block. G is the correct syntax to access it from a constructor

public class Car { class Engine { // insert code here } public static void main(String[] args) { new Car().go(); } private void go() { new Engine(); } void drive() { System.out.println("hi"); } } // Which, inserted independently at line 'insert code here', produces the output "hi"? (Choose all that apply.) A. { Car.drive(); } B. { this.drive(); } C. { Car.this.drive(); } D. { this.Car.this.drive(); } E. Engine() { Car.drive(); } F. Engine() { this.drive(); } G Engine() { Car.this.drive(); }

C Because first the Foo instance is created, which means the Foo constructor runs and prints foo. Next, the makeBar() method is invoked, which creates an anonymous Bar. This means the Bar constructor runs and prints 'bar', and finally an instance is created (of an anonymous subtype of Bar), on which the go() method is invoked. Note that the line (new Bar() {}).go(); creates a tiny anonymous inner class, a subtype of Bar.

public class Foo { Foo() { System.out.print("foo"); } class Bar{ Bar() { System.out.print("bar"); } public void go() { System.out.print("hi"); } } public static void main(String[] args) { Foo f = new Foo(); f.makeBar(); } void makeBar() { (new Bar() {} ).go(); } } // What is the result? A. Compilation fails B. An error occurs at runtime C. foobarhi D. barhi E. hi F. foohi

B, C. The code generates a stream of integers 0...49. In B, we first filter numbers divisible by 2, which gets us the evens, and then we filter by numbers divisible by 5, which gets us 0, 10, 20, 30, 40, which is five numbers. In C, we filter numbers divisible by 10, which gets us 0, 10, 20, 30, 40, which is five numbers.

public class GenAndFilter { public static void main(String[] args) { IntStream s = IntStream.iterate(0, i -> i+1).limit(50) // L1 long count = s.count(); System.out.println("Num: " + count); } } Which code fragment(s), inserted independently at L1, will cause the code to compile and output the result: "Num: 5" (Choose all that apply). A. .filter(i -> (i % 5) == 0); B. .filter(i -> (i % 2) == 0).filter(i -> (i % 5) == 0); C. .filter(i -> (i % 10) == 0); D. .map(i -> (i % 10) == 0); E. .map(i -> (i % 2) == 0).map(i -> (i % 5) == 0);

B. The code compiles without issue, so Option D is incorrect. The first print() statement refers to value in the Deeper class, so 5 is printed. The second and third print() statements actually refer to the same value in the Deep class, so 2 is printed twice. The prefix Matrix. is unnecessary in the first of the two print() statements and does not change the result. For these reasons, Option B is the correct answer.

public class Matrix { private int level = 1; class Deep { private int level = 2; class Deeper { private int level = 5; public void printReality() { System.out.print(level); System.out.print(" "+Matrix.Deep.this.level); System.out.print(" "+Deep.this.level); } } } public static void main(String[] bots) { Matrix.Deep.Deeper simulation = new Matrix().new Deep().new Deeper(); simulation.printReality(); } } // What is the output? A. 1 1 2 B. 5 2 2 C. 5 2 1

C The Penguin class includes a member inner class Chick. Member inner classes cannot include static methods or variables. Since the variable volume is marked static, the member inner class Chick does not compile. Note that the variable volume referenced in the chick() method is one defined in the Penguin outer class. If the static modifier was removed from the volume variable in the Chick class, then the rest of the code would compile and run without issue, printing Honk(1)! at runtime.

public class Penguin { private int volume = 1; private class Chick { private static int volume = 3; void chick() { System.out.print("Honk("+Penguin.this.volume+")!"); } } public static void main(String... eggs) { Penguin pen = new Penguin(); final Penguin.Chick littleOne = pen.new Chick(); littleOne.chick(); } } // What is the output? A. Honk(1)! B. Honk(3)! C. The code does not compile. D. The code compiles but the output cannot be determined until runtime.

A. The inner class Sorter must be declared static to be called from the static method main(). If Sorter had been static, answer E would be correct

public class Pockets { public static void main(String[] args) { String[] sa = {"nickel", "button", "key", "lint"}; Sorter s = new Sorter(); for (String s1 : sa) System.out.println(s1); Arrays.sort(sa, s); for (String s2 : sa) System.out.println(s2); } class Sorter implements Comparator<String> { public int compare(String a, String b) { return b.compareTo(a); } } } // What is the result? A. Compilation fails B. button key lint nickel nickel lint key button C. nickel button key lint button key lint nickel D. nickel button key lint nickel button key lint E nickel button key lint nickel lint key button

C,E,D B is incorrect because java.lang.Object doesn't implement java.lang.Comparable. F is incorrect because compare() can take only two arguments. G is incorrect because the Collections.reverse(collection) method does not require that a collection be sorted: It might be List<Comparable> In comparison with Collections.reverseOrder(); which returns Comparator<T>, e.g.: Comparator<String> reverse = Collections.reverseOrder();

B. The java.lang.Object class implements the java.lang.Comparable interface. C. Many commonly used classes in the Java API (such as String, Integer, Date, and so on) implement the java.lang.Comparable interface. D. If your class implements java.lang.Comparable but you don't explicitly override Comparable's method, collections containing elements of your class will be sorted in natural order by default. E. When using the java.util.Comparator interface, you will typically create a separate class for every different sort sequence you want to implement, or you will use a lambda expression to stand in for the Comparator. F. The java.util.Comparator interface's method can take either one or two arguments. G. The binarySearch(), reverse(), and reverseOrder() methods in the java.util.Collections class all require that the collection is sorted before the method can be invoked successfully. Which are true? (Choose all that apply.)

D,E. The lambda expression takes two ints and returns an int (on line 4), so an IntBinaryOperator is appropriate (D). The abstract method in the IntBinaryOperator functional interface is applyAsInt. E also works because the primitive ints are autoboxed and unboxed. If you want to avoid autoboxing, D is the better solution. A, B, and C are incorrect. A is incorrect; apply is not the correct function name for a primitive functional interface. B is incorrect because a BiFunction of this type would return an Integer, not an int. C is incorrect because accept is not the correct function name for an operator (it is the function name for a Consumer).

Given the following code fragment: *_____________* tt = (a, b) -> { // line 1 return axa + bxb; }; int ss = tt.*_____________*(2, 3); // line 4 System.out.println("Sum of squares: " + ss); // Which would you insert in line 1 and line 4 so that the code produces 13? A. IntBinaryOperator, apply B. BiFunction<Integer, Integer>, apply C. IntBinaryOperator, accept D. IntBinaryOperator, applyAsInt E. BinaryOperator<Integer>, apply

C. Using EJavaGuru's ejg.course will refer to its instance variable. Using Online.course will refer to the static variable course from Online. Code on line n1 compiles successfully and prints OCA. Because the variables defined in an interface are implicitly static and final, the variable 'duration' can be accessed as EJavaGuru.duration. So, code on line n2 compiles successfully and prints 2. However, a class can't define static and instance variables with the same name. For example the following class won't compile: class EJavaGuru { String course; static String course; } Therefore using EJavaGuru.course will result in a compilation error, so n3 doesn't compile.

What is the output? (Choose all that apply) interface Online { String course = "OCP"; int duration = 2; } class EJavaGuru implements Online { String course = "OCA"; public static void main(String args[]) { EJavaGuru ejg = new EJavaGuru(); System.out.print(ejg.course); // n1 System.out.print(EJavaGuru.duration); // n2 System.out.print(EJavaGuru.course); // n3 } } a Compilation fails at line n1. b Compilation fails at line n2. c Compilations fails at line n3. d Code prints "OCA2". e Code prints "OCP2". f Code throws a runtime exception.

A, B An interface can neither define aconstructor nor a static initializer block.

What is true about interfaces? (Choose all that apply.) A They force an implementing class to provide its own specific functionality. B An object of a class implementing an interface can be referred to by its own type. C An interface can define constructors to initialize its final variables. D An interface can define a static initializer block to initialize its variables.

B,E. B is correct because a method-local inner class can be abstract, although it means a subclass of the inner class must be created if the abstract class is to be used (so an abstract method-local inner class is probably not useful). E is correct because a method-local inner class works like any other inner class—it has a special relationship to an instance of the enclosing class, thus it can access all members of the enclosing class.

Which are true about a method-local inner class? (Choose all that apply.) A. It must be marked final B. It can be marked abstract C. It can be marked public D. It can be marked static E. It can access private members of the enclosing class

A, C. First, the access modifier of TRUE's implementation of getNickName() is package-private, but the abstract method signature has a protectedmodifier. Since package-private is a more restrictive access than protected, the override is invalid and the code does not compile. Second, the enum list is not terminated with a semicolon.

Which lines contain compilation errors? (Choose all that apply) public enum Proposition { A: TRUE(-10) { @Override String getNickName() { return "RIGHT"; }}, B: FALSE(-10) { public String getNickName() { return "WRONG"; }}, C: UNKNOWN(0) { @Override public String getNickName() { return "LOST"; }} D: private final int value; E: Proposition(int value) { this.value = value; } F: public int getValue() { return this.value; } G: protected abstract String getNickName(); }

C, F. E is incorrect as interfaces are assumed to be abstract, and abstract and final can never be used together.

Which of the following are true of interfaces? (Choose all that apply.) A. They can extend other classes. B. They cannot be extended. C. They enable classes to have multiple inheritance. D. They can only contain abstract methods. E. They can be declared final. F. All members of an interface are public.

B. Option A is incorrect because the lambda expression is missing a semicolon (;) at the end of the return statement. Option C is incorrect because the local variable testis used without being initialized. Option D is also incorrect. The parentheses are required on the left-hand side of the lambda expression when there is more than one value or a data type is specified. Option B is the correct answer and the only valid lambda expression.

Which of the following is a valid lambda expression? A. r -> {return 1==2} B. (q) -> true C. (x,y) -> {int test; return test>0;} D. a,b -> true

A,B,C,D Option (a) is correct. If you add a method to your interface, all the classes that implement the interface will fall short on the definition of the newly added method and will no longer compile. Option (b) is correct. If you add a nonabstract method to your base class, you can break its subclasses. If a subclass method has the same name (protected for example) as the newly added method in the base class (public), which doesn't qualify as a valid overloaded or overriding method, the subclass won't compile. Option (c) is correct. When you work with an interface type, you're free to work with any object that implements the interface. Option (d) is correct. Objects of all subclasses can be assigned to a reference variable of its abstract or nonabstract base class. So code that works with the abstract base class will work with objects of any of its subclasses

Which of the following options are correct? A If you add a method to your interface, you'll break all the classes that implement it. B If you add a nonabstract method to a base abstract class, its subclasses might not always succeed to compile. C When you work with an interface type, you decouple from its implementation. D Code that works with a reference variable of an abstract base class works with any object of its subclasses.

B. An enum cannot be marked abstract, nor can any of its values, but its methods can be marked abstract, making Option B the correct answer. Note that if an enum contains an abstract method, then every enum value must include an override of this method.

Which of the following properties of an enum can be marked abstract ? A. The enum class definition B. An enum method C. An enum value D. None of the above

A enums can have constructors and variables.

enum Animals { DOG("whoof"), CAT("meow"), FISH("burble"); String sound; Animals(String sound) { this.sound = sound; } } public class TestEnum { static Animals a; public static void main(String[] args) { System.out.println(a.DOG.sound + ", " + a.FISH.sound); } } // What is the result? A. woof burble B. Multiple compilation errors C. Compilation fails due to an error on line 2 D. Compilation fails due to an error on line 3

D. The application contains a compilation error. The case statements incorrectly use the enum name as well as the value, such as DaysOff.ValentinesDay. Since the type of the enum is determined by the value of the variable in the switch statement, the enum name is not allowed and throws a compilation error when used. For this reason, Option D is correct. If the enum name 'DaysOff' was removed, the application would output 12, since the lack of any break statements causes multiple blocks to be reached,and Option C would be the correct answer.

enum DaysOff { Thanksgiving, PresidentsDay, ValentinesDay } public static void main(String... unused) { final DaysOff input = DaysOff.Thanksgiving; switch(input) { default: case DaysOff.ValentinesDay: System.out.print("1"); case DaysOff.PresidentsDay12: System.out.print("2"); } } // What is the output? A. 1 B. 2 C. 12 D. None of the above

B. If the program is called with a single input WEST, then WEST would be printed at runtime. If the program is called with no input, then the compass array would be of size zero, and an ArrayIndexOutOfBoundsException would be thrown at runtime. Finally, if the program is called with a string that does not match one of the values in Direction, then an IllegalArgumentException would be thrown at runtime. The only result not possible is south, since the enum value is in uppercase, making Option Bthe correct answer.

enum Direction { NORTH, SOUTH, EAST, WEST; }; public class Ship { public static void main(String[] compass) { System.out.print(Direction.valueOf(compass[0])); } } // Which of the following results is NOT a possible output? A. WEST is printed. B. south is printed. C. An ArrayIndexOutOfBoundsException is thrown at runtime. D. An IllegalArgumentException is thrown at runtime.


संबंधित स्टडी सेट्स

LPNC 103: integumentary disorders and burn questions

View Set

FLUID AND ELECTROLYTE TICKET TO TEST

View Set

Business 1305: Module 4 Computer Concepts Exam

View Set