7

I'm looking for a solution, that allows to protect the default methods from inheritance. The easiest solution could be - extend from class and etc... but in my case it's not possible.

Can someone suggest how to solve this problem? Could there be any workarounds?

Atm I have following code, which needs to be reworked (if/any possible):

public interface MyInterface1 {
    default boolean isA(Object obj) {
         return (boolean) obj.equals("A") ? true : false;
    }

    default boolean isB(Object obj) {
         return (boolean) obj.equals("B") ? true : false;
    }
}

public class MyClass extends MyLogic implements MyInterface, MyInterface1 {
// this class allows to inherit methods from both interfaces,
// but from my perspective i'd like to use the methods from MyInterface1 as it is,
// with a 'protection' from inheritance. is that possible?
}
10
  • 2
    1. Are you trying to achieve some sort of multiple inheritance? It's gonna blow up in your face, rest of the Java language isn't suited for that. 2. I am not sure whether it's gonna work, but did you try to see what happens when you put "final" keyword on default methods? Jan 9, 2017 at 21:02
  • 4
    No need for all that verbosity, just say return obj.equals("B");. Jan 9, 2017 at 21:04
  • 2
    What does this even mean? The interface methods have to be inherited regardless of whether or not they have a default implementation.
    – Brick
    Jan 9, 2017 at 21:13
  • 2
    I don't understand what it means to "protect the default methods from inheritance." Do you mean you want to disallow classes providing their own implementations? Do you mean classes implementing your interface should not have those methods at all? Or what? Jan 9, 2017 at 21:17
  • 2
    @FilipMalczak you cannot use final on method declarations in an interface.
    – Lew Bloch
    Jan 9, 2017 at 22:18

4 Answers 4

7

You seem to want a way to write your interface so that implementing classes cannot provide their own implementations of its default methods. There is no way to do this, and indeed it runs counter to the purpose of interfaces in general and default members in particular.

The point of default methods is to provide a way to add methods to existing interfaces without instantly breaking all their existing implementations. Generally speaking, this is a binary compatibility issue, not a functionality issue. There's no particular reason to suppose in general that default implementations can provide the intended functionality, but without them, even old code that doesn't rely on the new methods at all is incompatible with interface revisions that add methods.


I think you have a factoring issue. Rather than trying to force classes to provide a specific implementation of a specific method -- which cannot even refer to that class's members, except possibly others defined by the same interface -- you should provide the common methods in a class of their own. After all, since you want all classes involved to provide identical implementations, it doesn't matter which class's implementations you actually use. Moreover, there is therefore no particular usefulness in marking any given class as providing implementations of the well-known methods.

Example:

public class MyImplementation1 {
    public static boolean isA(Object obj) {
         return obj.equals("A");
    }

    public static isB(Object obj) {
         return obj.equals("B");
    }
}

// Wherever needed, use as MyImplementation1.isA(o), etc.

You can do this even if you want these pre-baked implementations to operate in terms of the other methods of your interface. In that case, just add an argument to the fixed methods that provides the object to operate on. Perhaps that's what the obj arguments in your example were supposed to be; in that case, this may be closer to what you're after:

public interface MyInterface3 {
    public String someInterfaceMethod();
}

public class MyImplementation2 {

    public static boolean isA(MyInterface3 subject) {
         return subject.someInterfaceMethod().equals("A");
    }

    public static boolean isB(MyInterface3 subject) {
         return subject.someInterfaceMethod().equals("B");
    }
}
6

You can't. At least if you restrict yourself to a pure-java-compiler solution.

And the reason is because it was not designed to do that: the purpose is to add new methods to existing interface (like java.util.Collection) without breaking the implementations. That way, we have sort(), stream(), forEach() on Collection.

If you were to allow such thing (forbidding implementation), then it would means a change in the interface would result in a compilation error for implementation (because they would override the method, method that would been rendered final). That was not the purpose.

There are several other options to achieve that, depending on your need:

  • Abstract class with final method being the previously default method.
  • Testing the default behavior using unit testing.
  • Testing the possible implementation and check they don't override it.

The last case can probably be done easily with Reflections: you would have to list all implementations, and check for each interface's default method that there is no overriding using Reflections.

3

I take it you mean you want to write a class that uses the default methods of an interface, but does not inherit them.

In your example code, you attempted to use the default methods by implementing the interface. When you implement an interface, by design you also inherit all its methods. This is the Liskov Substitution Principle. By implementing the interface you are telling your users that all instances of your class are substitutable for instances of the interface. But if the interface default methods weren't inherited, this wouldn't be true, so you would be lying to users of your class.

To have your class use the interface's default methods without inheriting them, don't implement the interface! Instead, use a helper class that does:

public interface MyInterface1 {
    default boolean isA(Object obj) {
        return obj.equals("A");  // or "A".equals(obj) to avoid NullPointerException
    }

    default boolean isB(Object obj) {
        return obj.equals("B");
    }
}

public class MyClass extends MyLogic implements MyInterface {

    private static class Helper implements MyInterface1 {
        void doSomeWork() {
            // do something that calls isA() and isB()...
        }
    }

    public void someMethodOfMyClass() {
        // ...
        Helper.doSomeWork();
        // ...
    }
}
0

No, This is not possible due to the way java implements the interface (pun intended). For more information as to the reason for this, see the answers to this question Why is "final" not allowed in Java 8 interface methods?

However here are some other ways to guide a developer not to override a default method:

  1. A source code comment

//Do not inherit please

  1. A javadoc comment
4
  • You can't avoid inheriting. Did you mean "Do not override"? Jan 9, 2017 at 21:16
  • @MarrieteCowby12 please take a look on this: blog.joda.org/2016/09/… what do you think?
    – Malakai
    Jan 9, 2017 at 21:22
  • 2
    @reborn very useful article and thanks for bringing it in, but although its true that a private method cannot be overridden by a class implementing that interface, but the class also won't have access to that method since its modifier is private, so unless your case is where you don't want the implementing class to use the default method, then the private modifier won't help.
    – SteelToe
    Jan 9, 2017 at 21:28
  • 2
    Hence why "private default - compile error" (from the cited article).
    – Lew Bloch
    Jan 9, 2017 at 22:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.