Interface vs Class - methods visibility

0

I've done a job for school and it's working perfectly.

In the code I have some private methods. Do I need to create an Interface of this class to hide these private methods or can they be in the same class as the public methods?

At this point I have all the methods (public and private) in the same class, but my classmate is insisting that you have to create an Interface to hide private methods.

    
asked by anonymous 14.05.2015 / 12:51

1 answer

5

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.

    
14.05.2015 / 15:58