can a method be declared with static type argument in java ? if no, why?
ex:
class A
{
void m(static int x)
{
System.out.println(x);
}
}
can a method be declared with static type argument in java ? if no, why?
ex:
class A
{
void m(static int x)
{
System.out.println(x);
}
}
I don't believe this is possible and I cannot think of any valid use case for doing it.
It may make sense to make the method static in order to implement a singleton pattern.
class A
{
static void m(int x)
{
System.out.println(x);
}
}
Then it could be used without having to instantiate A as follows:
A.m(1);
Alternatively you might want to make x immutable to avoid unexpected behavior. This would be done using "final" as follows:
class A
{
void m(final int x)
{
System.out.println(x);
}
}
But making x static would serve no purpose.
No it won't be allowed (compiler error) and it makes sense as well. The static keyword means that a variable will have only one instance in its scope and that instance is invisible outside that scope. Neither of this makes sense for a function argument.
§6.7.5.3/2: "The only storage-class specifier that shall occur in a parameter declaration is register."
Static members are considered as class level members and gets loaded in memory during class loading, which means it is desirable that it shouldn't have dependency on the class instances.
So your class has member method m
which need a parameter
to be passed to execute the method body.
If you declare a static member for it that doesn't make any sense because it doesn't have any existence outside the method, class has no information about it load time which severely violates all the rules stated above.