-4

what will be the advantages and disadvantages of putting public with static methods ? As in any case We can access those using class name !

dinesh kandpal
  • 738
  • 7
  • 16
  • 6
    Static and access level modifiers are two different, unrelated things. – Maroun Aug 08 '17 at 06:28
  • @MarounMaroun thats what i am asking what will be the affect of putting public / default(none) with static methods ? – dinesh kandpal Aug 08 '17 at 06:30
  • Making them [public](https://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html) is one thing, and making them [static](https://docs.oracle.com/javase/tutorial/java/javaOO/classvars.html) is another thing. – Maroun Aug 08 '17 at 06:30
  • 1
    @dineshkandpal read more about access modifiers. and nothing to do with static or non static – soorapadman Aug 08 '17 at 06:31
  • @dineshkandpal access level is not different for static methods – Maurice Perry Aug 08 '17 at 06:31
  • Possible duplicate of [In Java, difference between default, public, protected, and private](https://stackoverflow.com/questions/215497/in-java-difference-between-default-public-protected-and-private) –  Aug 08 '17 at 06:40

3 Answers3

3

Without specifying an access control modifier, members of a class (static as instance) use by default the package private modifier.

You should refer to the Controlling Access to Members of a Class documentation :

Access level modifiers determine whether other classes can use a particular field or invoke a particular method. There are two levels of access control:

At the top level—public, or package-private (no explicit modifier).

At the member level—public, private, protected, or package-private (no explicit modifier).

Why a static method should necessarily be public ?
As for instance methods, you may also need to make them private or package private.

static has nevertheless a corner case : the protected static modifier should be avoided as misleading and contradictory in the intention.

davidxxx
  • 125,838
  • 23
  • 214
  • 215
2

They are not. And no, you cannot access private static methods from another class.

Maurice Perry
  • 9,261
  • 2
  • 12
  • 24
1

As Maroun has mentioned, access level modifiers are different than the static modifier.

By default, methods and variables are package-private when there is no access modifier. This means that they are restricted to your "package" or your project.

public means that all methods in all packages can see/use them.

private means that the method can only be used by that class.

The static modifier means that the class doesn't need to be instantiated to use the method/variable.

For a more in depth article on modifiers, please refer to this website: https://www.tutorialspoint.com/java/java_modifier_types.htm

Levi Muniz
  • 389
  • 3
  • 16