Home > Enterprise >  How to make methods that are implemented in a class from an interface be private?
How to make methods that are implemented in a class from an interface be private?

Time:02-24

I have an interface "FlowControl" as it defines the methods should be implemented by those classes to process the data in correct order. Now, as those classes have some functions that can be called from other classes, i want to make those interface methods private inside each class. But doing so results in error in intellij. I am a beginner in java so please help me or is there any other better approach for achieving this?

public interface FlowControl{
    void writeData();
}


public class CustomerInfo() implements FlowControl{
    **private** void writeData(){
        //Some functionality private to each class
    }
}

CodePudding user response:

You can't. Saying that CustomerInfo implements FlowControl literally says that CustomerInfo must have a public writeData() method. The only way for it not to have that method public is for it not to implement the interface.

If you need a FlowControl within the CustomerInfo class, but not have it implement the interface and expose the method, make the FlowControl a field within the CustomerInfo class:

public class CustomerInfo {
  private final FlowControl myFlowControl = /* implement the interface as an anonymous class/lambda */;

  // Rest of the class... use myFlowControl where you need it.
}

This is an example of preferring composition over inheritance. To put this another way: now CustomerInfo has a FlowControl (composition); not, CustomerInfo is a FlowControl (inheritance).

CodePudding user response:

As Andy mentioned, you cannot do this in Java. The only viable alternative that I can think of is using an abstract class "FlowControl " where you define these methods as "protected" and in "CustomerInfo" you extend the abstract "FlowControl". by doing that, those methods will be protected and unavailable from outside.

  • Related