GuruKulki
GuruKulki

Reputation: 26428

what is the use of having public methods when the class is having a default access modifier?

as for my observation when the class itself is having default access modifier, what is the use of having public methods in it. the java compiler could have stopped using public methods in default class. is there any reason for that?

Upvotes: 15

Views: 3579

Answers (3)

SohailAQ
SohailAQ

Reputation: 1040

It is a beautiful combination of Security and Usability packed in one.

I would mark a Class with default access if I want it to have a, well, package access (so that no other package can use it or better change the code) and marking a method public, I am making the method accessible to all other classes regardless of the package they belong to.

How does that help? A class which is secure enough to perform all the complex code implementation and usable enough to give the output to the user who wants to use it.

How can anyone use that? Well you write code to help them use it by creating a public class which extends this default class. You Instantiate this public Subclass in any package (after importing of-course) and this has all the methods marked public.

You have a class which does your magic which everyone can use without giving anyone else a hint of how you got it done!

Upvotes: 6

Dan Dyer
Dan Dyer

Reputation: 54515

The non-public class might implement a public interface. This would mean that classes outside of the package could not create an instance of this class or create references of that type, but they would still be able to invoke methods on it if passed an instance.

For example, a public factory class might create an instance of an non-public class in its package and return it.

Upvotes: 10

Jonathan Feinberg
Jonathan Feinberg

Reputation: 45364

One reason: if your class implements some interface (or extends some abstract class with abstract public methods), then you may not reduce the visibility of those implemented methods.

Upvotes: 9

Related Questions