HI all,
I have a small doubt regarding statics in JAVA. Consider the following
code.
public Class A
{
int x=10;
void printX()
{
System.out.println ("x is :" + x);
}
public static void main()
{
printX();
}
}
This results in a Compiler error, since the compiler detects that the
non-static ( uses instance variables) method printX() is used in static
context (static void main()). This is OK.
Using the same concept the following code must also report a Compiler
error. But it works
public Class A
{
int x=10;
void printX()
{
System.out.println ("x is :" + x);
}
public static void main()
{
Class a = new A();
a.printX(); // works fine ??????????
}
}
Can anyone please explain how ?
Regards,
Sarathy
Timothy Bendfelt - 26 Jul 2006 21:55 GMT
a.printX() is not a static context. It executes in the context of
instance "a" of class A.
> HI all,
>
[quoted text clipped - 41 lines]
> Regards,
> Sarathy
Steve W. Jackson - 26 Jul 2006 21:56 GMT
> HI all,
>
[quoted text clipped - 41 lines]
> Regards,
> Sarathy
In the second example, main is not calling the non-static method.
Instead, it has created an instance of the class A and is calling the
*instance method* printX. That's what it's supposed to do.
= Steve =

Signature
Steve W. Jackson
Montgomery, Alabama
cp - 26 Jul 2006 22:07 GMT
> HI all,
>
[quoted text clipped - 41 lines]
> Regards,
> Sarathy
Static context in general doesnt allow references to variables and methods
that are not static. Static methods are methods, which should only use the
given paramter and necessary local variables to compute something eg. an
addition.
The reason why the second example works is because you make an instance of
the class. Calling non-static functions from a static context requires an
instance of the given class. Static methods are a permenant attachment to a
given object and because of that they can call instance methods only if they
use their own object references, which in this case is the instantiation of
the given obejct A.