Options in the interface

If I want to make the method in my interface optional, is it possible to do this? How?

+7
source share
9 answers

Indicate in Javadoc that implementing classes can throw a UnsupportedOperationException.

+7
source

You can not.

However, you can create a second interface and transfer the "optional" method to that interface.

Thus, a class can implement one or both interfaces.

+6
source

You cannot make the method optional in the interface, although you can do one of the following:

  • Make your interface abstact class and implement only the "optional" method

  • Deploy the interface from your classes and throw a NotImplementedException (or the like)

  • Make an interface with an inner class that contains an optional method

+4
source

As indicated by others: you cannot. But you can extend the interfaces so you can create something like:

public interface InterfaceA { void methodA(); } public interface InterfaceB extends InterfaceA { void methodB(); } 

This way you can use InterfaceA to implement classes with only one specific method and InterfaceB when you can use both methods.

But of course, it all depends on your design.

+4
source

No, you can’t.

The interface is a contract and must be implemented.

+2
source

No, It is Immpossible. The closest thing you can get to not implement a method in an interface is to throw an exception immediately. You need to rethink the design of your type.

+1
source

you cannot do this 8) From What is an interface?

If your class claims to implement an interface, all methods defined by this interface must appear in the source code before the class successfully compiles.

Perhaps you should use an abstract abstract class .

+1
source

You can create an abstract class of the same interface, the same class can call the same methods, but not necessarily.

+1
source

Impossible, as far as I know.

0
source

All Articles