Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

access modifier of interface method

 
Tusshar Fasate
Ranch Hand
Posts: 81
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why methods of Interface are public not protected?
 
Marco Ehrentreich
best scout
Bartender
Posts: 1294
IntelliJ IDE Java Scala
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi tushartrue,

the method declarations of an interface are by default public abstract because it only makes sense when a class is able to implement these methods. It's not allowed and wouldn't make much sense if you could declare a private method for example because abstract private methods could never get implemented by any concrete class!

Marco
 
Tusshar Fasate
Ranch Hand
Posts: 81
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Marco,i was asking about protected modifier?
 
Ramya Chowdary
Ranch Hand
Posts: 252
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Its not perfect answer.

See,Interfaces are for imposing a rule among programmers.

How your Module will communicate with mine,its just exposing the interface to some system(i.e how to interact),not implementation.

Implementation could be anything as long as the interface ( i mean how to communicate) is same.

Interfaces are for standard way of Communication( there are lots of other things)

So,You shouldn't hide it right.

So, Interfaces methods must be public.
 
Ramya Chowdary
Ranch Hand
Posts: 252
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Again,
Protected is used when you're going for INHERITANCE.

Interfaces are mainly used for Supporting Composition over Inheritance.So, when you doing composition, you depend on public methods.


It doesn't make sense to have protected method,right.
 
Marco Ehrentreich
best scout
Bartender
Posts: 1294
IntelliJ IDE Java Scala
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Oh sorry... the protected modifier is not an option for interface methods. They can only be public and are implicitly public abstract whether you declare it with these modifiers or not!

@Pratap: You're right, I only explained the technical aspect of interface method declarations because I thought this is what tushartrue wanted to know. Of course you'll usually use a public interface to propagate your public API or contract of your code to other programmers.

Marco
 
Tusshar Fasate
Ranch Hand
Posts: 81
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Pratap and Marco
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic