JAVA OCA ‎1Z0-808 Chapter 5 - Class Design

¡Supera tus tareas y exámenes ahora con Quizwiz!

1. The type of the object determines which properties exist within the object in memory. 2. The type of the reference to the object determines which methods and variables are accessible to the Java program.

Object vs. reference rules

F Abstract methods must be overridden by a concrete subclass.

T/F Abstract methods cannot be overridden by a concrete subclass.

It fails to compile because the return types are not covariant. It fails to compile because of a static modifier mismatch between the two methods.

Why won't this compile? public class Rodent { protected static Integer chew() throws Exception { System.out.println("Rodent is chewing"); return 1; } } public class Beaver extends Rodent { public Number chew() throws RuntimeException { System.out.println("Beaver is chewing on wood"); return 2; } }

In this example, we see that HarborSeal is an abstract class and compiles without issue. Any class that extends HarborSeal will be required to implement all of the methods in the HasTail and HasWhiskers interface. Alternatively, LeopardSeal is not an abstract class, so it must implement all the interface methods within its defi nition. In this example, LeopardSeal doesn't provide an implementation for the interface methods, so the code doesn't compile.

Will this compile? public interface HasTail { public int getTailLength(); } public interface HasWhiskers { public int getNumberOfWhiskers(); } public abstract class HarborSeal implements HasTail, HasWhiskers { } public class LeopardSeal implements HasTail, HasWhiskers { }

Yes

Will this compile? public class Bunny implements Hop { public void printDetails() { System.out.println(Hop.getJumpHeight()); } }

1. A default method may only be declared within an interface and not within a class or abstract class. 2. A default method must be marked with the default keyword. If a method is marked as default, it must provide a method body. 3. A default method is not assumed to be static, final, or abstract, as it may be used or overridden by a class that implements the interface. 4. Like all methods in an interface, a default method is assumed to be public and will not compile if marked as private or protected.

Default method rules

Every single line of this example doesn't compile. The fi rst line doesn't compile for two reasons. First, it is marked as final, which cannot be applied to an interface since it confl icts with the assumed abstract keyword. Next, it is marked as private, which confl icts with the public or default required access for interfaces. The second and third line do not compile because all interface methods are assumed to be public and marking them as private or protected throws a compiler error. Finally, the last line doesn't compile because the method is marked as final and since interface methods are assumed to be abstract, the compiler throws an exception for using both abstract and final keywords on a method.

Does this compile? private final interface CanCrawl { private void dig(int depth); protected abstract double depth(); public final void surface();

No. Casting an object from a superclass to a subclass requires an explicit cast.

Does this compile? public class Lemur extends Primate(){ } Primate primate = lemur; Lemur lemur2 = primate;

Yes. Casting an object from a superclass to a subclass requires an explicit cast.

Does this compile? public class Lemur extends Primate(){ } Primate primate = lemur; Lemur lemur3 = (Lemur)primate;

one

How many public classes per file does Java allow?

1. Interface variables are assumed to be public, static, and final. Therefore, marking a variable as private or protected will trigger a compiler error, as will marking any variable as abstract. 2. The value of an interface variable must be set when it is declared since it is marked as final.

Interface variables rules

1. Interfaces cannot be instantiated directly. 2. An interface is not required to have any methods. 3. An interface may not be marked as final. 4. All top-level interfaces are assumed to have public or default access, and they must include the abstract modifier in their definition. Therefore, marking an interface as private, protected, or final will trigger a compiler error, since this is incompatible with these assumptions. 5. All nondefault methods in an interface are assumed to have the modifiers abstract and public in their definition. Therefore, marking a method as private, protected, or final will trigger compiler errors as these are incompatible with the abstract and public keywords.

Rules for defining an interface.

1. An interface that extends another interface, as well as an abstract class that implements an interface, inherits all of the abstract methods as its own abstract methods. 2. The first concrete class that implements an interface, or extends an abstract class that implements an interface, must provide an implementation for all of the inherited abstract methods

Rules for inheriting an interface

1. Like all methods in an interface, a static method is assumed to be public and will not compile if marked as private or protected. 2. To reference the static method, a reference to the name of the interface must be used.

Static interface methods rules.

T

T/F A class may implement multiple interfaces.

T

T/F A class that implements two interfaces containing static methods with the same signature will still compile at runtime, because the static methods are not inherited by the subclass and must be accessed with a reference to the interface name.

F Concrete classes can be both final and not final.

T/F A concrete subclass cannot be marked as final

T A concrete class must implement all inherited abstract methods.

T/F A concrete subclass must implement all inherited abstract methods.

F A superclass may have already implemented an inherited interface, so the concrete subclass would not need to implement the method.

T/F A concrete subclass must implement all methods defined in an inherited interface.

T All objects extend java.lang.Object, so if a method takes that type, any valid object, including null, may be passed.

T/F A method that takes a parameter with type java.lang.Object will take any reference.

F A reference to an object requires an explicit cast if referenced with a subclass. If the cast is to a superclass reference, then an explicit cast is not required.

T/F A reference to an object may be cast to a subclass of the object without an explicit cast.

F Some cast exceptions can be detected as errors at compile-time, but others can only be detected at runtime.

T/F All cast exceptions can be detected at compile-time.

F Due to the nature of polymorphism, a public instance method can be overridden in a subclass and calls to it will be replaced even in the superclass it was defined.

T/F By defining a public instance method in the superclass, you guarantee that the specific method will be called in the parent class at runtime.

T

T/F Every class has at least one constructor. In the case that no constructor is declared, the compiler will automatically insert a default no-argument constructor.

T Because of polymorphic parameters, if a method takes the superclass of an object as a parameter, then any subclass references may be used without a cast.

T/F If a method takes a superclass of three objects, then any of those classes may be passed as a parameter to the method.

T

T/F If the parent doesn't have a no-argument constructor and the child doesn't define any constructors, the compiler will throw an error and try to insert a default no-argument constructor into the child class.

T

T/F If the parent doesn't have a no-argument constructor, the compiler requires an explicit call to a parent constructor in each child constructor.

T

T/F In Java, the first statement of every constructor is either a call to another constructor within the class, using this(), or a call to a constructor in the direct parent class, super().

T

T/F In Java, the parent constructor is always executed before the child constructor.

F

T/F Number is a subclass of Integer.

T

T/F default methods cannot be marked as static and require an instance of the class implementing the interface to be invoked. They can also not be marked as final or abstract, because they are allowed to be overridden in subclasses but are not required to be overridden

F Concrete classes are, by definition, not abstract.

T/F A concrete subclass can be declared as abstract.

In the case that no constructor is declared, the compiler will automatically insert a default no-argument constructor. Java compiler automatically inserts a call to the no-argument constructor super() if the first statement is not a call to the parent constructor.

The following three class and constructor definitions are equivalent. Why?

1. Abstract classes cannot be instantiated directly. 2. Abstract classes may be defined with any number, including zero, of abstract and nonabstract methods. 3. Abstract classes may not be marked as private or final. 4. An abstract class that extends another abstract class inherits all of its abstract methods as its own abstract methods. 5. The first concrete class that extends an abstract class must provide an implementation for all of the inherited abstract methods.

What are the rules for defining an abstract class?

1. Abstract methods may only be defined in abstract classes. 2. Abstract methods may not be declared private or final. 3. Abstract methods must not provide a method body/implementation in the abstract class for which is it declared. 4. Implementing an abstract method in a subclass follows the same rules for overriding a method. For example, the name and signature must be the same, and the visibility of the method in the subclass must be at least as accessible as the method in the parent class.

What are the rules for defining an abstract method?

1. The method in the child class must have the same signature as the method in the parent class. 2. The method in the child class must be at least as accessible or more accessible than the method in the parent class. 3. The method in the child class may not throw a checked exception that is new or broader than the class of any exception thrown in the parent class method. 4. If the method returns a value, it must be the same or a subclass of the method in the parent class, known as covariant return types. 5. The method defined in the child class must be marked as static if it is marked as static in the parent class (method hiding). Likewise, the method must not be marked as static in the child class if it is not marked as static in the parent class (method overriding).

What are the rules for hiding methods?

1. The method in the child class must have the same signature as the method in the parent class. 2. The method in the child class must be at least as accessible or more accessible than the method in the parent class. 3. The method in the child class may not throw a checked exception that is new or broader than the class of any exception thrown in the parent class method. 4. If the method returns a value, it must be the same or a subclass of the method in the parent class, known as covariant return types.

What are the rules for overriding methods?

The compiler will throw an error. There is an exception to this rule, though: if the subclass overrides the duplicate default methods, the code will compile without issue—the ambiguity about which version of the method to call has been removed.

What happens If a class implements two interfaces that have default methods with the same name and signature?

A hidden method occurs when a child class defi nes a static method with the same name and signature as a static method defi ned in a parent class.

What is a hidden method?

A virtual method is a method in which the specifi c implementation is not determined until runtime. In fact, all non-final, nonstatic, and non-private Java methods are considered virtual methods, since any of them can be overridden at runtime. What makes a virtual method special in Java is that if you call a method on an object that overrides a method, you get the overridden method, even if the call to the method is on a parent reference or within the parent class.

What is a virtual method?

An interface is an abstract data type that defi nes a list of abstract public methods that any class implementing the interface must provide. An interface can also include a list of constant variables and default methods.

What is an interface?

Java supports polymorphism, the property of an object to take on many different forms. To put this more precisely, a Java object may be accessed using a reference with the same type as the object, a reference that is a superclass of the object, or a reference that defi nes an interface the object implements, either directly or through a superclass. Furthermore, a cast is not required if the object is being reassigned to a super type or interface of the object.

What is polymorphism?

The first statement of every constructor is a call to another constructor within the class using this(), or a call to a constructor in the direct parent class using super().

What is the first statement of every constructor?

The code compiles and runs without issue. The printName() method is an overload in Spider, not an override, so both methods may be called. The call on line 8 references the version that takes an int as input defined in the Spider class, and the call on line 9 references the version in the Arthropod class that takes a double. Therefore, SpiderArthropod is output.

What is the output of the following code? 1: class Arthropod 2: public void printName(double input) { System.out .print("Arthropod"); } 3: } 4: public class Spider extends Arthropod { 5: public void printName(int input) { System.out.print("Spider"); } 6: public static void main(String[] args) { y 7: Spider spider = new Spider(); 8: spider.printName(4); 9: spider.printName(9.0); 10: } 11: }

False. This code compiles and runs without issue, outputting false, so option B is the correct answer. The first declaration of isBlind() is as a default interface method, assumed public. The second declaration of isBlind() correctly overrides the default interface method. Finally, the newly created Owl instance may be automatically cast to a Nocturnal reference without an explicit cast, although adding it doesn't break the code

What is the output of the following code? 1: interface Nocturnal { 2: default boolean isBlind() { return true; } 3: } 4: public class Owl implements Nocturnal { 5: public boolean isBlind() { return false; } 6: public static void main(String[] args) { 7: Nocturnal nocturnal = (Nocturnal)new Owl(); 8: System.out.println(nocturnal.isBlind()); 9: } 10: }

In this example, the fi rst method, eatMeat(), doesn't compile because it is marked as default but doesn't provide a method body. The second method, getRequiredFood Amount(), also doesn't compile because it provides a method body but is not marked with the default keyword.

Will this compile? public interface Carnivore { public default void eatMeat(); public int getRequiredFoodAmount() { return 13; } }

You should consider the object as the entity that exists in memory, allocated by the Java runtime environment. Regardless of the type of the reference you have for the object in memory, the object itself doesn't change. For example, since all objects inherit java.lang.Object, they can all be reassigned to java.lang.Object.

Object vs. reference?

1. Casting an object from a subclass to a superclass doesn't require an explicit cast. 2. Casting an object from a superclass to a subclass requires an explicit cast. 3. The compiler will not allow casts to unrelated types. 4. Even when the code compiles without issue, an exception may be thrown at runtime if the object being cast is not actually an instance of that class.

Rules for casting variables.

Methods marked as final, they can't be overriden.

What are final methods?

java.lang.Object

What class do all classes inherit from?

If no super() call is declared in a constructor.

When will java insert a no-argument super() as the first statement of the constructor?

As the first statement of the constructor.

Where can be the super() call in the constructor used?

, D, E, F. First off, options B and C are incorrect because protected and public methods may be overridden, not hidden. Option A is correct because private methods are always hidden in a subclass. Option D is also correct because static methods cannot be overridden, only hidden. Options E and F are correct because variables may only be hidden, regardless of the access modifier

Which of the following may only be hidden and not overridden? (Choose all that apply) A. private instance methods B. protected instance methods C. public instance methods D. static methods E. public variables F. private variables

A, B, D, E. The blank can be filled with any class or interface that is a supertype of TurtleFrog. Option A is a superclass of TurtleFrog, and option B is the same class, so both are correct. BrazilianHornedFrog is not a superclass of TurtleFrog, so option C is incorrect. TurtleFrog inherits the CanHope interface, so option D is correct. All classes inherit Object, so option E is correct. Finally, Long is an unrelated class that is not a superclass of TurtleFrog, and is therefore incorrect

Which of the following statements can be inserted in the blank line so that the code will compile successfully? (Choose all that apply) public interface CanHop {} public class Frog implements CanHop { public static void main(String[] args) {________________ frog = new TurtleFrog(); } } public class BrazilianHornedFrog extends Frog {} public class TurtleFrog extends Frog {} A. Frog B. TurtleFrog C. BrazilianHornedFrog D. CanHop E. Object F. Long

A. The code compiles and runs without issue, so options C, D, and E are incorrect. The trick here is that the method fly() is marked as private in the parent class Bird, which means it may only be hidden, not overridden. With hidden methods, the specific method used depends on where it is referenced. Since it is referenced within the Bird class, the method declared on line 2 was used, and option A is correct. Alternatively, if the method was referenced within the Pelican class, or if the method in the parent class was marked as protected and overridden in the subclass, then the method on line 9 would have been used.

A. Bird is flying B. Pelican is flying C. The code will not compile because of line 4. D. The code will not compile because of line 5. E. The code will not compile because of line 9.

A, C, F. First off, Cobra is a subclass of Snake, so option A can be used. GardenSnake is not defined as a subclass of Snake, so it cannot be used and option B is incorrect. The class Snake is not marked as abstract, so it can be instantiated and passed, so option C is correct. Next, Object is a superclass of Snake, not a subclass, so it also cannot be used and option D is incorrect. The class String is unrelated in this example, so option E is incorrect. Finally, a null value can always be passed as an object value, regardless of type, so option F is correct.

A. new Cobra() B. new GardenSnake() C. new Snake() D. new Object() E. new String("Snake") F. null

Won't compile, because the super() command may only be used as the first statement of the constructor.

public class Zoo { public Zoo() { System.out.println("Zoo created"); super(); } }

The code will not compile because of line 2.. This may look like a complex question, but it is actually quite easy. Line 2 contains an invalid definition of an abstract method. Abstract methods cannot contain a body, so the code will not compile and option B is the correct answer. If the body {} was removed from line 2, the code would still not compile, although it would be line 8 that would throw the compilation error. Since dive() in Whale is abstract and Orca extends Whale, then it must implement an overridden version of dive(). The method on line 9 is an overloaded version of dive(), not an overridden version, so Orca is an invalid subclass and will not compile.

What is the output of the following code? 1: public abstract class Whale { 2: public abstract void dive() {}; 3: public static void main(String[] args) { 4: Whale whale = new Orca(); 5: whale.dive(); 6: } 7: } 8: class Orca extends Whale { 9: public void dive(int depth) { System.out.println("Orca diving"); } 10: }

A, D, E. Interface variables are assumed to be public static final; therefore, options A, D, and E are correct. Options B and C are incorrect because interface variables must be public—interfaces are implemented by classes, not inherited by interfaces. Option F is incorrect because variables can never be abstract

What modifiers are assumed for all interface variables? (Choose all that apply) A. public B. protected C. private D. static E. final F. abstract

B. All interface methods are implicitly public, so option B is correct and option A is not. Interface methods may be declared as static or default but are never implicitly added, so options C and F are incorrect. Option D is incorrect—void is not a modifier; it is a return type. Option E is a tricky one, because prior to Java 8 all interface methods would be assumed to be abstract. Since Java 8 now includes default and static methods and they are never abstract, you cannot assume the abstract modifier will be implicitly applied to all methods by the compiler

What modifiers are implicitly applied to all interface methods? (Choose all that apply) A. protected B. public C. static D. void E. abstract F. default

C. The code compiles without issue, so option A is wrong. Option B is incorrect, since an abstract class could implement HasVocalCords without the need to override the makeSound() method. Option C is correct; any class that implements CanBark automatically inherits its methods, as well as any inherited methods defined in the parent interface. Because option C is correct, it follows that option D is incorrect. Finally, an interface can extend multiple interfaces, so option E is incorrect.

Which statements are true about the following code? 1: interface HasVocalCords { 2: public abstract void makeSound(); 3: } 4: public interface CanBark extends HasVocalCords { 5: public void bark(); 6: }. A. The CanBark interface doesn't compile. B. A class that implements HasVocalCords must override the makeSound() method. C. A class that implements CanBark inherits both the makeSound() and bark() methods. D. A class that implements CanBark only inherits the bark() method. E. An interface cannot extend another interface.

B, C, E, F. Option A is wrong, because an abstract class may contain concrete methods. Since Java 8, interfaces may also contain concrete methods in form of static or default methods. Although all variables in interfaces are assumed to be public static final, abstract classes may contain them as well, so option B is correct. Both abstract classes and interfaces can be extended with the extends keyword, so option C is correct. Only interfaces can contain default methods, so option D is incorrect. Both abstract classes and interfaces can contain static methods, so option E is correct. Both structures require a concrete subclass to be instantiated, so option F is correct. Finally, though an instance of an object that implements an interface inherits java.lang. Object, the interface itself doesn't; otherwise, Java would support multiple inheritance for objects, which it doesn't. Therefore, option G is incorrect.

Which statements are true for both abstract classes and interfaces? A. All methods within them are assumed to be abstract. B. Both can contain public static final variables. C. Both can be extended using the extend keyword. D. Both can contain default methods. E. Both can contain static methods. F. Neither can be instantiated directly. G. Both inherit java.lang.Object.

The fi rst example shows a class trying to extend an interface that doesn't compile. The second example shows an interface trying to extend a class, which also doesn't compile.

Whill this compile? public interface CanRun {} public class Cheetah extends CanRun {} public class Hyena {} public interface HasFur extends Hyena {}

Actually, the code will compile. Although the definition of methods on lines 2 and 5 vary, both will be converted to public abstract by the compiler. Line 4 is fine, because an interface can have public or default access. Finally, the class Falcon doesn't need to implement the interface methods because it is marked as abstract. Therefore, the code will compile without issue.

Why won't this compile? 1: public interface CanFly { , 2: void fly(); 3: } 4: interface HasWings { 5: public abstract Object getWindSpan(); 6: } 7: abstract class Falcon implements CanFly, HasWings { 8: }

The code will not compile because of lines 3 and 4. The method declaration for eatGrass() on line 3 is incorrect because the method has been marked as static but no method body has been provided. The method declaration for chew() on line 4 is also incorrect, since an interface method that provides a body must be marked as default or static explicitly. The interface variable amount is correctly declared, with public and static being assumed and automatically inserted by the compiler.

Why won't this compile? 1: public interface Herbivore { 2: int amount = 10; 3: public static void eatGrass(); 4: public int chew() { 5: return 13; 6: } 7: }

No. s you can see, without an explicit reference to the name of the interface the code will not compile, even though Bunny implements Hop. In this manner, the static interface methods are not inherited by a class implementing the interface.

Will this compile? public class Bunny implements Hop { public void printDetails() { System.out.println(getJumpHeight()); } }

No. Throws ClassCastException at runtime. This code creates an instance of Rodent and then tries to cast it to a subclass of Rodent, Capybara. Although this code will compile without issue, it will throw a ClassCastException at runtime since the object being referenced is not an instance of the Capybara class. The thing to keep in mind in this example is the object that was created is not related to the Capybara class in any way.

Will this compile? public class Rodent { } public class Capybara extends Rodent { public static void main(String[] args) { Rodent rodent = new Rodent(); Capybara capybara = (Capybara)rodent; } }


Conjuntos de estudio relacionados

Cardiovascular System (Mastering A&P)

View Set

SY0-401:1 TS Quiz Network Security

View Set

Taylor Review Questions - Wounds/Skin Integrity

View Set

Ch. 20 Anxiolytic and Hypnotic Agents

View Set

Ch. 10 - Pay for Performance: Incentive Rewards HR 312

View Set

OPS - CHAPTER 7 - Cap Openings, Shell Designs & Closure Methods

View Set