No they are not allowed to use non static features of the class, they can only call
static methods and can use static data.
No, a static method in Java cannot directly access non-static (instance) members of its class. Static methods are associated with the class itself, rather than with any specific instance of the class. They are called using the class name, not an instance of the class.
If you want to access non-static features (fields or methods) within a static method, you need to create an instance of the class and then access those non-static members through the instance.
Here’s an example:
public class MyClass {
private int nonStaticVariable;
public static void staticMethod() {// Cannot directly access non-static variable like this:
// int value = nonStaticVariable; // This will result in a compilation error
// To access non-static variable, create an instance of the class:
MyClass instance = new MyClass();
int value = instance.nonStaticVariable;
}
public void nonStaticMethod() {
// Non-static method can directly access non-static variables
int value = nonStaticVariable;
}
}
In the example above, staticMethod
cannot directly access nonStaticVariable
, so it creates an instance of MyClass
and then accesses the non-static variable through that instance. On the other hand, nonStaticMethod
can directly access the non-static variable without the need for an instance because it is a non-static method.