I have one doubt on Static methods
Most common line that i often read about Static methods is
"Remember that you cannot directly refer to any of the instance variables in the class
within a static method. This is because a static method can be executed when no
objects of the class have been created, and therefore no instance variables exist."
i tried accessing instance variable in static method, i thought compiler would not allow that , but i could easily
compile and run the code
Code:
package source.hibernate.utilities;
public class Practice {
public String name;
public int age;
public static int getAge(Practice prac)
{
return prac.age;
}
}
/*------------------------------------------------*/
package source.hibernate.utilities;
public class Test
{
public static void main(String argc[])
{
Practice prac =new Practice();
prac.age=10;
System.out.println(Practice.getAge(prac));
}
}
Now in above code both the classes Practice and Test are in same package
i tried printing age which is a non-static member variable of class Practice through
a static method getAge().
i could compile and execute the above code with out any error.
Now this is contradicting my understanding for static methods.
static methods cannot access any instance variable,
but if i think it as a normal non-static method, where i provide it with an reference to an instance and then print the age
using that reference then its perfect!
shouldn't compiler be checking any non static reference made to a static methods at compile time.
And why java allows a static method to be called from object.
I guess my understanding for static methods is still not perfect.