0

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
    }
}
  • 1
    "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." That sounds like a non-sequitur to me. Please clarify why you want the methods to be private. – Jon Skeet Feb 23 '22 at 17:46
  • @JonSkeet because these interface methods are writing information related to some data but they are called according to different conditions. so i don't want them to be called mistakenly without fulfilling the conditions. – Muhammad Zeeshan Feb 23 '22 at 18:18
  • Sounds like they shouldn't be part of an interface then. If you don't want to be able to write `FlowControl x = new CustomerInfo(); x.writeData();`... then `CustomerInfo` shouldn't implement `FlowControl`. – Jon Skeet Feb 23 '22 at 18:20
  • @JonSkeet thank you for shading light on it! Actually i have multiple classes and they process the data in similar ways so i though it would be a good idea to make them all implement an interface so the coding would be consistent. Nevertheless, Now i know i should change it. – Muhammad Zeeshan Feb 23 '22 at 18:30

2 Answers2

2

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

Andy Turner
  • 137,514
  • 11
  • 162
  • 243
0

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.

Mahdi
  • 1,871
  • 2
  • 24
  • 41