Stuck in Java
Stuck in Java

Reputation: 202

What is the use of public method inside class with default level access?

I was just wondering if there is any reason java allow public methods inside class with default level access? I couldn't find any yet. Any knowledge sharing will be appreciated.

Upvotes: 4

Views: 171

Answers (2)

Evgeniy Dorofeev
Evgeniy Dorofeev

Reputation: 136072

A class with default level access may implement an interface, in this case its methods need to be public. Or it may be a bean so it will need public getter and setter methods for properties

Upvotes: 1

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726919

This is the only way a default-level access class could implement an interface.

The situation when classes with default access are used as helpers is very common. If you try implementing an interface using default access methods with the same signature, you would get this error:

attempting to assign weaker access privileges; was public

In addition, it is a good idea to use public for clarity everywhere a method is designed for access from outside the class, including private classes declared inside other classes or methods.

Upvotes: 3

Related Questions