I have a call to a function and the background of that call is yellow and it says "static member being accessed by instance reference," but it works perfectly without errors.
Should I have to solve that somehow or is it okay?
Here is a code sample:
class A {
static int x = 2;
...
}
Instantiation is some other file:
A a = new A();
a.x;
Instance method can access static variables and static methods directly. Static methods can access the static variables and static methods directly.
Since static variables belong to a class, we can access them directly using the class name. So, we don't need any object reference. We can only declare static variables at the class level. We can access static fields without object initialization.
A static method can only access static data members and static methods of another class or same class but cannot access non-static methods and variables.
A static method cannot reference instance member variables directly. A static method cannot call an instance method directly. Subclasses cannot override static methods. We cannot use keywords this and super in a static method.
This warning happens when you have something like this:
class A {
static int x = 2;
}
...
A a = new A();
a.x; // accessing static member by instance
You should access the static member x
via the class (or interface) instead:
A a = new A();
A.x;
Static members belong to the class, not to a particular instance.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With