Pratiksha Jadhav
Pratiksha Jadhav

Reputation: 185

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

I don't want to make my class abstract for this. For e.g. 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?

Upvotes: 2

Views: 1945

Answers (4)

Alexey Romanov
Alexey Romanov

Reputation: 170805

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

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

Upvotes: 0

Jiri Tousek
Jiri Tousek

Reputation: 12440

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.

Upvotes: 6

Peter Lawrey
Peter Lawrey

Reputation: 533660

You can have default methods, e.g.

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.

Upvotes: 0

Eran
Eran

Reputation: 393916

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();
        }
        ...
    }
    

Upvotes: 8

Related Questions