I'm reading SCJP by Kathy Sierra and Bert Bates and it says on pg. 21 that "The public modifier is required if you want the interface to have public rather than default access". Is this true? If yes, then the interface methods (which are always public) only accessible if the interface is in the same package of the implementing class...? Since that is the meaning of the default access modifier...I'm a bit confused on this.
3
votes
If you want the interface to have public access, then you need to say so. The individual members of the interface, however, are always public.
– cHao
So, for example if the interface itself has default access, then how do it's methods get used outside of the package its being implemented in. The interface in that case wouldn't even be visible to the implementing class....so it doesn't make sense to me why its methods would be public if it has default access :-(
– user1142130
The interface would be visible to any other class in the package. Any class in the package that wanted to implement the interface would of course declare the relevant methods as public. Outsiders wouldn't be able to use the interface -- default access is effectively "for internal use" -- but they could call the methods it defines, as they'd be public on the class. Assuming, of course, that the class is public.
– cHao
2 Answers
2
votes
Is it true that if you don't specify an access modifier for an interface, that interface will have default access?
Yes that is true. Java types/fields/methods (in class) have package-level access if access modifier is not specified. Members defined in inteface type are public by-default.
Read tutorial - Controlling Access to Members of a Class.
1
votes
Here the interface
itself is package protected
but the methods are always public
by default
interface Foo
{
void bar(); // this is always public and nothing else
}
Here the interface
is public
as well as the methods
public interface Foo
{
void bar(); // this is always public and nothing else
}
you can declare public void bar();
or void bar();
they mean the same thing, personally, I always put the public
because explicit is always better than implicit