0

In Java, in the body of an interface, must methods and variables be declared as having public access? If so, what could be gained from declaring the interface access without the 'public' access modifier i.e. leaving access as the default access?

As an example, what could be gained from writing

interface DefaultAccess {

as opposed to

public interface PublicAccess {

?

danger mouse
  • 1,457
  • 1
  • 18
  • 31
  • Interface members are public by default, but interface without access modifier is accessed only in the same package. – peterremec Jan 07 '15 at 07:26
  • 2
    Your example is different from your question. Are you asking about the interface itself being public? Or are you asking about its methods and fields? Note that all the members of an interface are public - you can't have them any other way. – Dawood ibn Kareem Jan 07 '15 at 07:26
  • Thanks all. To clarify, the query that I was getting at was: if a class method that implements an interface method/variable is always public, what can be gained from declaring the interface itself as default access i.e. non-public? According to the query http://stackoverflow.com/questions/161633/should-methods-in-a-java-interface-be-declared-with-or-without-a-public-access-m – danger mouse Jan 08 '15 at 05:30
  • it appears that there is nothing technically to be gained by declaring an interface as non-public, so I now have a better understanding of this. – danger mouse Jan 08 '15 at 05:36

2 Answers2

1

Interface methods are implicitly public, even if you don't declare them that way.

The interface itself has the same rules as a class. Public works as usual, and package private (i.e. no modifier) means the interface can only be used by classes from the same package.

Kayaman
  • 72,141
  • 5
  • 83
  • 121
1

If the interface is not public it cannot be accessed outside the package which includes this interface.

This might help you understand it better: Java Access Modifiers

FaizanHussainRabbani
  • 3,256
  • 3
  • 26
  • 46
Kiki
  • 2,243
  • 5
  • 30
  • 43