Java Magazine, May/June 2018
ORACLE COM JAVAMAGAZINE MAY JUNE 2018 94 fix this Base b new Sub And if you did the compiler expects the object referred to by the variable b to behave according to the rules defined for a Base object The fact that the variable b actually refers to an instance of Sub is allowed but it must not cause surprises In the light of this background lets look at the three categories of change individually First consider the accessibility of a method The Base class gives default access to the method doStuff If an override makes the method more accessible no surprises will arise the method will still be accessible in the places you expect it to be accessible In fact if you had a reference of Sub type the doStuff method would be more accessible but that is fine too The thing referred to by the variable b lets you do what you expect to do So making the method public or generally making an overriding method more accessible is acceptable By contrast making the method private would cause a problem Using the variable b you expect to be able to invoke the method doStuff but if the object to which b refers were actually an instance of Sub the invocation would be rejected by the Sub object and it would fail at runtime This would definitely be a surprise and is therefore not acceptable So the general rule is that a method may be overridden by another method that is not less accessible This rule is sufficient to tell you that option A and option E are incorrect Considering exceptions Javas exception mechanism requires that any checked exception that might be thrown by a method must be declared This is required so that the compiler knows about the exception and is able to verify that the caller of the method handles the exception either by using a catch block or by declaring that it too throws the exception Imagine a situation based on the assignment shown in question 2 in which the overriding method in Sub throws a checked exception Code of the form b doStuff would be analyzed by the compiler using the information defined in the Base class The compiler would decide that no checked exceptions are possible and it would not require the programmer to add a try catch or any other exception handling However given that the variable b actually refers to a Sub object if the overriding method did in fact throw a checked exception the compiler would have been
You must have JavaScript enabled to view digital editions.