1

I have a stateless abstract base class that should not be inherited from outside of its package:

package foo;

public abstract class Foo
{
    // some abstract methods
    // one concrete method
    // no state

    // Prevent classes outside of package foo from inheriting
    Foo()
    {
    }
}

Now that Java 8 supports default methods in interfaces, I would like to convert the abstract class to an interface. With interfaces, is it also possible to prevent inheritance outside of the current package?

fredoverflow
  • 256,549
  • 94
  • 388
  • 662
  • You can have package-private interfaces (of course, then no one outside the package can even call it). – Thilo Jun 23 '14 at 08:42
  • @Thilo `Foo` itself must be public in my case. – fredoverflow Jun 23 '14 at 08:43
  • Any chance to split into public and internal interfaces (with default methods on the internal one)? Internal can still `extend` the public interface. – Thilo Jun 23 '14 at 08:44
  • Why do you like to prevent the inheritance? Security or Design? – Grim Jun 23 '14 at 09:01
  • I don't think that there is a concise and obvious solution (i.e. none that does not involve hacky contortions, like adding a "dummy method" that expects a package-private class as one argument). In http://stackoverflow.com/a/22721577/3182664 I pointed out that cases like this are one of the few justifications that still exist for using abstract classes at all. – Marco13 Jun 23 '14 at 09:04
  • @PeterRader I have a scenario similar to `EnumSet` with `RegularEnumSet` and `JumboEnumSet` as the only valid implementations. – fredoverflow Jun 23 '14 at 09:34
  • @Marco13 That dummy trick is hilarious :) Did you come up with it? – fredoverflow Jun 23 '14 at 09:42
  • Hopefully, "hilarious" implies that you do **NOT** take this serious. I just wanted to emphasize that certain aspects of *visibility* can only be modeled properly with (abstract) classes, and not with interfaces (although this will rarely be really necessary) – Marco13 Jun 23 '14 at 09:46
  • @Marco13 Still, if you put that trick into an answer, you have my upvote ;) – fredoverflow Jun 23 '14 at 09:47
  • @FredOverflow So it is more a design that a security reason. – Grim Jun 23 '14 at 10:08

1 Answers1

0

From the java tutorial:

.. All abstract, default, and static methods in an interface are implicitly public, so you can omit the public modifier.

It means that you can't unless you restrict the interface visibility to package. But i guess that you can't.

package foo;

interface Foo
{
}

I suppose that you could write a custom annotation (somelink like @InstanciableOnlyInMyPackage) and put it on the interface. And then using raise a compiler error using Annotation Processing Tool.

gontard
  • 28,720
  • 11
  • 94
  • 117