This week's book giveaway is in the Kotlin forum.
We're giving away four copies of Kotlin in Action and have Dmitry Jemerov & Svetlana Isakova on-line!
See this thread for details.
Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

why can't a class make an interface method private?  RSS feed

 
Steve Harmison
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
All methods of an interface must be public. And if the method must remain public in a class that implemets it, then that is bad, because we might not want it to be public!
So what is the reason behind Java not allowing interface methods to become private inside a class?

Thank you.
 
Tony Docherty
Bartender
Posts: 3268
82
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Because the purpose of interfaces is to publicly declare a behaviour that a class has, therefore it doesn't make sense to be able to restrict the access to the method.

If you do need to do this then it's most likely that you have a design issue to resolve. Maybe splitting the interface into two (or more) parts and possibly having 1 extend the other would help. That way your class only needs to implement the interface(s) that defines the behaviour it has.
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
A couple times I found myself wanting to force a subclass to implement some method that really ought to be private. Is that what you're looking to do? Java won't let us, and it turns out it doesn't make much sense. You have to give implementers the freedom to implement any way they please.
 
Steve Harmison
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks everyone.
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Oh, I probably read you wrong. I was thinking you meant to put a private method in an interface, but maybe you meant for the implementing class to make a public interface method private in the implementation.

The interface is often called a contract, which just means it makes promises to clients that must be kept. If I write a method that depends on an interface, I rely on the promise that all the interface methods will be available:

size() has to be there for all implementations of List. If you could write a new List implementation that made size private, and if you passed it into my method, what should happen? There's no good answer, so the compiler just doesn't let it happen. (Ok, there are some answers we only have to look at loosely typed languages to see, but Java isn't one of em.)
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!