Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

static member being accessed by instance reference

Tags:

java

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;
like image 612
diego Avatar asked Jul 04 '17 17:07

diego


People also ask

Can a static attribute be accessed inside of an instance method?

Instance method can access static variables and static methods directly. Static methods can access the static variables and static methods directly.

Can we access static members using object reference?

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.

Can you access static members from an instance of a class?

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.

Can static methods reference instance data?

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.


1 Answers

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.

like image 166
Alberto Trindade Tavares Avatar answered Sep 28 '22 07:09

Alberto Trindade Tavares