13
sealed class PI
{
  public static float number;
  static PI()
  { number = 3.141592653F; }
  static public float val()
  { return number; }
}
  1. What's the difference between public static and static public? Can they be used in any order?

  2. How would I use static public float val()?

    Does it get executed as soon as the class is initialized?

Ola Ström
  • 4,136
  • 5
  • 22
  • 41
Alex Gordon
  • 57,446
  • 287
  • 670
  • 1,062

6 Answers6

24

There's no difference. You're free to specify them in either order.
However, I find that most developers tend to use:

public static

and NOT static public.

Ola Ström
  • 4,136
  • 5
  • 22
  • 41
Jesper Larsen-Ledet
  • 6,625
  • 3
  • 30
  • 42
9

About the ordering of modifiers

They can be used in any order. It's just a stylistic choice which one you use. I always use visibility first, and most other code does too.

About the second question:

static public float val()

This is just a static function. You call it with PI.val(). You just don't need an instance of the class to call it, but call it on the class directly. A static function does not receive a this reference, can't be virtual, it's just like a function in a non OOP language, except that it's using the class as namespace.

CodesInChaos
  • 106,488
  • 23
  • 218
  • 262
8

Well, it is just like the name of a Person =) Calling Tom Mike or Mike Tom, no difference.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Singleton
  • 3,701
  • 3
  • 24
  • 37
  • 10
    Except perhaps if you're Sing Confu and they call you Confu Sing. –  Nov 10 '10 at 18:27
7

There is no difference. Their order is not important with respect to each other

JaredPar
  • 733,204
  • 149
  • 1,241
  • 1,454
5

To answer your second question, it should probably be written as

public static class Pi
{
    private static float pi = 0;

    public static float GetValue()
    {
        if (pi == 0)
            pi = 3.141592653F;   // Expensive pi calculation goes here.

        return pi;
    }
}

And call it thusly:

float myPi = Pi.GetValue();

The reason for writing such a class is to cache the value, saving time on subsequent calls to the method. If the way to get pi required a lot of time to perform the calculations, you would only want to do the calculations once.

Robert Harvey
  • 178,213
  • 47
  • 333
  • 501
4

With regards to the second question: The method is available without an instance of a class, it could be called thusly:

PI.val();

Because the class only has static members, the class should probably be a static class, and then it could never get initialized.

McKay
  • 12,334
  • 7
  • 53
  • 76