Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Agile forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Interfaces with default access

 
Trey Carroll
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello all,

I'm studying K&B and I just came across something that I thought might benefit the community.

K&B 1.5 pg 69 says
"Interfaces can be implemented by any class, from any inheritance tree".
That sounded fishy to me so I coded up a little sample app to test it.





The statement in K&B is very broad and seems to imply that any interface in any package will always be accessible to any other class. I started thinking that all interfaces must be public implicitly or something, but I have verified that this is not true. If you remove the public access modifier from the Testable interface in the code above, the Test class will no longer compile. You get this error:
pkg1.Testable is not public in pkg1; cannot be accessed from outside package
import pkg1.Testable;


The moral of the story is that the K&B statement is misleading. Interfaces can have default access; if they do you may not implement them from outside their own package.

Hope this is beneficial to someone else.
 
Pranav Bhatt
Ranch Hand
Posts: 284
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Interfaces can be implemented by any class, from any inheritance tree

I guess it implies that any class can implement the interface even if the inheritance trees are different. But for that still the interface should be visible or accessible. You can't access a interface in other package if it has default access modifier in some other package. Interfaces are implicitly abstract but not implicitly public. In K&B itself on page 21 you can find this comment too.

The public modifier is required if you want the interface to have public rather than default access.
.
 
Bear Bibeault
Author and ninkuma
Marshal
Pie
Posts: 64623
86
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Trey Carroll:
The moral of the story is that the K&B statement is misleading.
Not really. You misinterpreted it. This statement implies nothing about access modifiers. Rather it is pointing out that unlike base classes, interfaces do not need to be part of the inheritance hierarchy in order to be implemented.
 
Trey Carroll
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Now I understand what was meant by the statement.

Thank you for taking the time to clarify it for me.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic