IUnknown
IUnknown

Reputation: 9829

helper function for default interface method

I need to incorporate some helper methods to assist the default method of interface on Java 8 - for better code organization.
So the only available option seems to be to qualify them with 'static' - and thus leave them exposed to outside.
Is there a better way to achieve this - migrating to Java 9 is not an option.

Upvotes: 1

Views: 1072

Answers (1)

ernest_k
ernest_k

Reputation: 45339

If upgrading to a more recent version is an option for you, you may in fact be able to use private methods in an interface

In Java 9 and newer, interfaces allow private (non-abstract) methods. See JSL 9.4:

A method in the body of an interface may be declared public or private (§6.6). If no access modifier is given, the method is implicitly public...

And these private methods may be static too (same source):

...It is permitted for an interface method declaration to contain both private and static.


If you have to stay on Java 8, you could use package-private classes and methods (yes, this is not private to the type, but package-private is a better alternative)

public interface Interface {
    default void doSomething() {
        InterfaceHelper.doSomething();
    }
}

class InterfaceHelper {
    static void doSomething() { //package-private class and method

    }
}

Upvotes: 3

Related Questions