Quantcast
Channel: Pochampalli IT Labs
Viewing all articles
Browse latest Browse all 261

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

$
0
0
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;

publicclassNonStaticDataMemberInStaticMethod{

int a=10;// non static variable
publicstaticvoidmain(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;

publicclassNonStaticDataMemberInStaticMethod{

int a =10;//non static variable
publicstaticvoidmain(String args[]){

NonStaticDataMemberInStaticMethod myObj=new NonStaticDataMemberInStaticMethod();
System
.out.println(myObj.a);
}

}




- Sadakar Pochampalli 

Viewing all articles
Browse latest Browse all 261

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>