简体   繁体   中英

Is there any way not to implement interface methods in Java?

I don't want to make my class abstract for this. For eg I have class which want to implement 1 interface which has around 15-20 method declarations but only 4-5 methods are the ones which matter for my class.

Is there any other alternative to do this?

The alternatives (to making your class abstract) are:

  1. Supply default implementation to the interface methods you don't want to implement in your class within the interface itself (requires Java 8 or higher).

    For example:

     public interface YourInterface { ... default boolean someMethod () { return false; } ... } 
  2. Implement all the methods you don't want to implement with an empty body that throws an exception. This approach is common in the collections framework.

    For example:

     public class YourClass implements YourInterface { ... public boolean someMethod() { throw new UnsupportedOperationException(); } ... } 

If possible, fix the underlying design issue.

If you can make a useful class that only implements 5 methods out of 20, that hints at the interface being in fact a mess of many independent contracts. Separate those independent contracts into separate interfaces and use whatever is needed, wherever is needed instead of having one huge interface that you only implement partially.

You can have default methods, eg

interface Common {
    default void actionOne() {
        // nothing to do
    }
    // or
    default void actionTwo() {
        throw new UnsupportedOperationException("Must be implemented if used");
    }
}

or you can have multiple interfaces and only implement the ones which matter.

One option which other answers don't mention: you can do this by only creating the class at runtime, eg using java.lang.reflect.Proxy .

This should rarely be your first option, but it can be useful.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM