How to implement classes with private method?

Asked

Viewed 284 times

3

I am rewriting the code of an application seeking the best use of 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, because I have other classes that do the same function.

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

public class Classe implements Interface{

    @Override
    public metodoPublico (){
        ...
    }

    @Override
    private metodoPrivado (){
        ...
    }

}
  • Have you ever thought about using the "protected" access modifier instead of "private"? because who can implement or see such methods is only who inherits it.

2 answers

5


Interfaces do not serve this purpose. 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 at will, as long as it follows the contract to the public. Whether it will have a private method or not is a problem of the concrete class, it is deprived precisely for that reason. It makes no sense to require a private method.

If this method is really required in the public class API, make it public, if it is not, let the class implementer do it the way you think best.

Depending on the problem it may be useful to have an abstract class, but it would make more sense if this proven method is protected, and look there, this is almost always wrong too. But reinforcement, it depends on the case.

1

There is no way to implement private methods of an interface, since an interface is used for several classes equal to a recipe, an API, for each class to use in its own way, as it sees fit. So it wouldn’t make sense to have a private method.

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

There’s no distinction, they’ll always be public.

  • 1

    I’ll give the +1 but it got a bit cluttered the explanation. It would be better to say that the interface specifies a contract between the classes that implement this interface and the code that will make use of these classes, determining which public methods will be available to the client code. So it only makes sense for the interface to declare public methods.

  • 1

    Thanks @Piovezan , so your comment is as a complement to the reply :)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.