1

I have an interface with 2 methods say method1 and method2. I want to restrict the implementation of only method1 in class1 and method2 in class2 as shown below. Is it possible?

interface Interface1{ 
    method1(); 
    method2();
}
class Class1 implements Interface1{
    method1() {
        //method1 implementation
    }
    //method2 access is restricted
}
class Class2 implements Interface1{
    method2() {
        //method2 implementation
    }
    //method1 access is restricted
}
Anish B.
  • 9,111
  • 3
  • 21
  • 41
Wanderlust
  • 43
  • 4
  • i think you would have to split the two methods into separate interfaces – experiment unit 1998X Mar 23 '23 at 03:08
  • you could consider set method1 and method2 in Interface1 to be default methods that throw an exception (runtime etc) with an optional message (ie not implemented for this class), then override the method accordingly in whatever class. – experiment unit 1998X Mar 23 '23 at 03:12
  • What do you want to happen if you write: `new Class2().method1();`? – tgdavies Mar 23 '23 at 03:24
  • In Java, all methods have to have an implementation when an interface is implemented. It can be a default implementation in the interface or an implementation in a class or its superclass. In your case you can have an implementation for `method2` in `Class1` which throws `UnsupportedOperationException` . But this is not recommended practice as your interface will violate [SOLID principles](https://stackoverflow.com/questions/13692126/cant-seem-to-understand-solid-principles-and-design-patterns). Best practice would be to do as @experimentunit1998X mentioned to split the interface – josephjacobmorris Mar 23 '23 at 03:37

1 Answers1

0

By the definition of Interface,

An interface is a contract which means a class implementing an interface must implement all the abstract methods declared in the interface (or contract).

Therefore, your requirement is simply impossible to achieve.

Note:

From JDK 9 onwards, private concrete methods were introduced in the interface which helps to restrict the implementation of a concrete method in the implementation class.

But it only applies to concrete method implementations and not to abstract methods as abstract methods cannot be private.

Hence, it's still impossible to achieve.

Anish B.
  • 9,111
  • 3
  • 21
  • 41