javaimplements

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


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
    }
}

Solution

  • 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).