Reputation: 60691
sealed class PI
{
public static float number;
static PI()
{ number = 3.141592653F; }
static public float val()
{ return number; }
}
What's the difference between public static and static public? Can they be used in any order?
How would I use static public float val()
?
Does it get executed as soon as the class is initialized?
Upvotes: 13
Views: 10704
Reputation: 6723
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.
Upvotes: 27
Reputation: 108790
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.
Upvotes: 9
Reputation: 3679
Well, it is just like the name of a Person =) Calling Tom Mike or Mike Tom, no difference.
Upvotes: 8
Reputation: 180777
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.
Upvotes: 5
Reputation: 12604
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.
Upvotes: 4
Reputation: 754585
There is no difference. Their order is not important with respect to each other
Upvotes: 7