Interfaces are nothing more than purely abstract classes. That is, classes that do not have defined members (i.e. do not impose any implementation details), and all their methods are public and abstract (ie they establish a contract that the implementing class must offer to the consumer code). For this reason, a reference to an interface does not have access to any private member of the concrete class.
However, this is a sufficient condition to hide private members, but not required - it is perfectly possible to get encapsulation without user interfaces. The encapsulation by private
only does not apply to the class itself (obviously, because the class needs access to its own fields!) And - in case one class is internal to another ( inner class ) - to the "outside" class.
Here is an example of what is and is not encapsulated in various situations:
class Main {
private int podeAcessar;
interface IInterna { }
abstract class InternaAbstrata {
private int podeAcessar2;
}
class Interna extends InternaAbstrata implements IInterna {
private int podeAcessar3;
}
public static void main(String[] args) {
Main a; // pode acessar os campos privados
Interna b; // pode acessar os campos privados
InternaAbstrata c; // pode acessar os campos privados
IInterna d; // NÃO pode acessar os campos privados
Externa e; // NÃO pode acessar os campos privados
ExternaAbstrata f; // NÃO pode acessar os campos privados
IExterna g; // NÃO pode acessar os campos privados
}
}
interface IExterna { }
abstract class ExternaAbstrata {
private int naoPodeAcessar;
}
class Externa extends ExternaAbstrata implements IExterna {
private int naoPodeAcessar2;
}
As you can see in the example above, this statement that "... has to create an interface to hide private methods" is incorrect, since in both% and%% of cases the encapsulation occurs even without the use of interfaces.