Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Public methods

 
Sathvathsan Sampath
Ranch Hand
Posts: 96
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What is use of having public methods within package class?
 
Tony Alicea
Desperado
Sheriff
Posts: 3226
5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I don't know...
Maybe if the class wants to go public one day, its method(s) are already public. Or if it is extended, its methods can be overridden (just as would its protected methods)...
I'd like to read the opinions of others...
 
Sathvathsan Sampath
Ranch Hand
Posts: 96
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Just another question on similar lines... what does Java insist that all interface methods implemented by a class must have an access modifier as public even if it is a "package only" interface?
 
Adam Ratcliffe
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
The reason that Java insists that all interface methods implemented by a class have a modifier of public is because you can't have an access specifier that is more restrictive than that implicit in the abstract method declaration (public).
As public is already as non-restricted as you can get your stuck with this specifier for any class that realizes the interface.
Furthermore, interfaces have the function of separating design from implementation. Specifiying abstract methods as public gives you maximum flexibility in the choice of classes that you use to realize the interface.
Hope this helps
Adam
 
Sathvathsan Sampath
Ranch Hand
Posts: 96
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Adam,
If u can declare an interface as follows:
interface PackageOnly
{
packageOnlyMethod();
}
class Test implements PackageOnly
{
public packageOnlyMethod()
{
............ some code....
}
}
Out here u can see that access specifier is NOT more restrictive than that implicit in the abstract method declaration (package).
Further, if we do need to provide the flexibility u mentioned, then user who defined the interface can simply make it public rather than package.
So, I am still not very clear about why java insists interface methods be given a public access specifier when implimenting in a class. Could someone please help???
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic