Reputation: 31
Is it possible to access the private static method within the object creation scope? Something like the below snippet.
class A {
private static void func(int x) {
/*Some Code here*/
}
}
and call from another context, something like this :
new A(){{
func(2);
}};
The intent here is to facilitate for addition of more calls to func(int)
, with a differnt argument for each call, or to put simpler, some sort of builder for the object of type A
.
Something like this :
new A() { {
func(2);
}
{
func(3);
}
// ...
};
Is this possible to achieve ?
Upvotes: 1
Views: 1519
Reputation: 40056
I think it is something you can find out the answer easily by actually writing some simple piece of code and try it out yourself.
From my understanding (haven't tried) it is not possible.
I think you have to understand what is the meaning of:
new A() { { func(2); } }
This is anonymous inner class which is just like writing something like
class A_anonymous extends A {
{
func(2);
}
}
and do a
new A_anonymous();
Further look into the class definition, it is in fact translated to
class A_anonymous extends A {
public A_anonymous() {
func(2);
}
}
So the answer is obvious. If func() is a private method in A, then of course you cannot use it such way.
The way to solve is simply make the visibility of the method to be protected (or higher).
Upvotes: 1
Reputation: 13882
Is it possible to access the private static method within the object creation scope?
Yes.
Within constructor you can call a static method.
class AClass
{
private void static aMethod1()
{
}
private void static aMethod2()
{
}
public AClass()
{
aMethod1();
aMethod2();
}
}
Upvotes: 0