Java Reference
In-Depth Information
package library;
class ApiBase {
public static final int ANSWER = 42;
}
public final class Api extends ApiBase {
// private static final int ANSWER = 6 * 9;
}
package client;
import library.Api;
public class Client {
int answer = Api.ANSWER;
}
As written, this program compiles without error. If we uncomment the private declaration in
library.Api
, the client fails to compile:
client/Client.java:4: ANSWER has private access in library.Api
int answer = Api.ANSWER;
^
The new private field
Api.ANSWER
hides the public field
ApiBase.ANSWER
, which would otherwise
be inherited into
Api
. Because the new field is declared
private
, it can't be accessed from
Client
.
Many variations on this solution are possible. You can hide an instance field instead of a static
field, or a type instead of a field.
You can also solve this puzzle with obscuring. All the solutions involve reusing a name to break the
client.
Reusing names is dangerous; avoid hiding, shadowing, and obscuring.
Is this starting to
sound familiar? Good!
Search WWH ::
Custom Search