Search code examples
javainterface

is it possible to change modifier of variables and methods in interface


modifiers in variables in an interface are public, static, final by default. But how can I do if I want it to be private so that no other classes can call this variable


Solution

  • Declaring a class to implement an interface is a promise that this class provides these methods, or extensions thereof. Increasing/extending access to the methods is allowed, but decreasing access is not, because then we would break our promise.

    This is similar to classes and extensions of them, subclasses. A subclass has to provide all methods of the superclass with at least the visibility they were declared with.

    The reason for this is the statically typed nature of Java. If a type may differ from its initial declaration in such a way that it breaks (access to) the type, then it makes the whole static-typing obsolete.

    Fields (also called member variables) are different in the way that their access cannot be extended. Declaring another member variable of similar name on a subclass is exactly that, another variable. By doing this, you hide the superclass' variable, and you may have to use the keyword super to access it.