How to implement classes with private method?

3

I am rewriting the code of an application looking for the best use of the interfaces and I came across a problem:

I have a class that needs to have a private method and I want to create an interface for it, since I have other classes that do the same function.

In short: how do I create an interface that implements a class like this:

public class Classe implements Interface{

    @Override
    public metodoPublico (){
        ...
    }

    @Override
    private metodoPrivado (){
        ...
    }

}
    
asked by anonymous 13.07.2016 / 16:09

2 answers

5

Interfaces are not good for this. They must declare contracts that the public API of the class must follow. Private methods are implementation details and should not be required. The class is free to attend to what the interface requires as it wishes, provided the contract is followed by the public. If it is going to have private method or not, it is problem of the concrete class, it is deprived precisely for that reason. It makes no sense to require a private method.

If this method really is required in the public API of the class, make it public, if it is not, let the class implementer do whatever it thinks best.

Depending on the problem it may be useful to have an abstract class, but it would make more sense if the method is protected , booster, depends on the case.

    
13.07.2016 / 16:15
1

There is no way to implement private methods of an interface, since an interface is used for several classes as a recipe, an API, for each class to use in its own way, as you see fit. So it would not make sense to have a private method.

public interface Interface {
     void metodoPrivado();
     void metodoPublico();
}

There is no distinction, they will always be public.

    
13.07.2016 / 16:14