1

I define a static method f for class named a in java,

Could I also use it as a.f outside the class?

OR we could only use it as a help function within the class?

sjain
  • 23,126
  • 28
  • 107
  • 185
user3341953
  • 309
  • 1
  • 5
  • 14

3 Answers3

4

If that is a public static method, you can use it from anywhere outside the class.

If that is package-private (default), then you can use only it within that package.

Abimaran Kugathasan
  • 31,165
  • 11
  • 75
  • 105
2

...could I also use it as a.f outside the class?

Yes. You can use the static method if it is declared as public:

public static void f() {
    // ...
}

or if it is package-private (no modifier):

static void f() {
    // ...
}
Christian Tapia
  • 33,620
  • 7
  • 56
  • 73
1

Marking the method Public will make it accessible wherever you want.

Marking the method Protected will make it accessible in same package and also in subclasses Marking the method nothing that is keeping it default (no modifier)will make it visible inside same package

Wherever u try to access your method Just make sure that your class is also visible there!

Hope this helps! All the best

Vihar
  • 3,626
  • 2
  • 24
  • 47