Java Reference
In-Depth Information
// private static class String {}
public static String newString() {
return new String();
}
}
package client;
import library.Api;
public class Client {
String s = Api.newString();
}
As written, the program compiles without error. If we uncomment the private declaration of the
local class
String
in
library.Api
, the method
Api.newString
no longer has the return type
java.lang.String
, so the initialization of the variable
Client.s
fails to compile:
client/Client.java:4: incompatible types
found: library.Api.String, required: java.lang.String
String s = Api.newString();
^
Although the only textual change we made was to add a private class declaration, we indirectly
changed the return type of an existing public method, which is an incompatible API change. We
changed the meaning of a name used in our exported API.
Many variations on this solution are possible. The shadowed type could come from an enclosing
class instead of
java.lang
. You could shadow a variable instead of a type. The shadowed variable
could come from a
static import
declaration or an enclosing class.
It is possible to solve this puzzle without changing the type of an exported member of the library
class. Here is such a solution, which uses hiding in place of shadowing:
Search WWH ::
Custom Search