Monday 11 May 2020

Core Java : Cannot make a static reference to the non-static field

If you try to  access an instance variable or say non-static variable in a static method, you would end up with static reference error message.

For instance, in the following example, variable "a" is class variable/non-static instance variable and if accessed directly in the static method, say in this case it is main method, it would throw the reference exception.

NonStaticDataMemberInStaticMethod.java
package static1.method;

public class NonStaticDataMemberInStaticMethod {
 
 int a=10 ;// non static variable
 public static void main(String args[]) {
  System.out.println(a);
 }

}


Error Message:
Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
 Cannot make a static reference to the non-static field a

 at static1.method.NonStaticDataMemberInStaticMethod.main(NonStaticDataMemberInStaticMethod.java:7)

Solution:
1) Create an Object
2) Call/print the non static variable using object.

package static1.Variable;

public class NonStaticDataMemberInStaticMethod {

 int a =10;//non static variable
 public static void main(String args[]) {
  
  NonStaticDataMemberInStaticMethod myObj=new NonStaticDataMemberInStaticMethod();
  System.out.println(myObj.a);
 }
 
}




- Sadakar Pochampalli 

No comments:

Post a Comment