Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Interfaces in Java: cannot make implemented methods protected or private

I know that an interface must be public. However, I don't want that.

I want my implemented methods to only be accessible from their own package, so I want my implemented methods to be protected.

The problem is I can't make the interface or the implemented methods protected.

What is a work around? Is there a design pattern that pertains to this problem?

From the Java guide, an abstract class wouldn't do the job either.

like image 718
jbu Avatar asked Jan 08 '09 02:01

jbu


People also ask

Can interface be private or protected in Java?

Private members of an interface If the members of the interface are private you cannot provide implementation to the methods or, cannot access the fields of it in the implementing class. Therefore, the members of an interface cannot be private.

Can a interface in Java be protected?

During overriding, when a variable or method is protected, it can be overridden to other subclass using either a public or protected modifier only. Outer class and interface cannot be protected.

Can we have private and protected methods in interface?

Protected methods are intended for sharing implementation with subclasses. Interfaces have nothing to offer as far as implementation sharing goes, because they have no implementation at all. Therefore all methods on interfaces must be public.

Can Java interfaces have private methods?

As of Java 9, methods in an interface can be private. A private method can be static or an instance method, but it cannot be a default method since that can be overridden.


1 Answers

read this.

"The public access specifier indicates that the interface can be used by any class in any package. If you do not specify that the interface is public, your interface will be accessible only to classes defined in the same package as the interface."

Is that what you want?

like image 184
duffymo Avatar answered Sep 21 '22 17:09

duffymo