How can i restrict my clients with selected methods from the class?

Create 2 new classes extending Parent class and override methods which are not accessible and throw Exception from them. But then if 3rd client with different requirement, we have to create new subclass for them.

It is a bad solution because it violates Polymorphism and the Liskov Substitution Principle. This way will make your code less clear.

At first, you should think about your class, are you sure that it isn't overloaded by methods? Are you sure that all of those methods relate to one abstraction? Perhaps, there is a sense to separate methods to different abstractions and classes?

If there is a point in the existence of those methods in the class then you should use different interfaces to different clients. For example, you can make two interfaces for each client

interface InterfaceForClient1 {
  public void m1();
  public void m3();
  public void m5();
  public void m7();
  public void m9();
  public void m11();
}

interface InterfaceForClient2 {
  public void m2();
  public void m4();
  public void m6();
  public void m8();
  public void m10();
  public void m12();
}

And implement them in your class

class MyClass implements InterfaceForClient1, InterfaceForClient2 {
}

After it, clients must use those interfaces instead of the concrete implementation of the class to implement own logic.


You can create an Interface1 which defines methods only for Client1, and an Interface2 which defines methods only for Client2. Then, your class implements Interface1 and Interface2.

When you declare Client1 you can do something like: Interface1 client1. With this approach, client1 can accesses only methods of this interface.

I hope this will help you.