Why non-static context can't be accessible from static context in java? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Why non-static context can't be accessible from static context in java?

Whenever we try to access the non-static content from a static block then we get compile error. What is the reason behind this?

12th Apr 2017, 9:28 AM
Bhavesh Joshi
Bhavesh Joshi - avatar
1 Answer
+ 17
Static fields and methods are connected to the class itself and not its instances. If you have a class A, a 'normal' method b and a static method c and make an instance a of your class, the calls to A.c()and a.b() are valid. Method c() has so no idea, which instance is connected, so it cannot use non-static fields. The solution for you is, that you make your fields static or make your methods non-static. You main could look like this then: class Programm { public static void main(String[] args){ Programm programm = new Programm(); programm.start(); } public void start(){ // can now access non-static fields } } Source: StackOverflow
12th Apr 2017, 9:47 AM
Dev
Dev - avatar