Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Non-static variable this cannot be referenced from a static context" when creating an object

I wrote the below code to test the concept of classes and objects in Java.

public class ShowBike {     private class Bicycle {         public int gear = 0;         public Bicycle(int v) {             gear = v;         }     }      public static void main() {         Bicycle bike = new Bicycle(5);         System.out.println(bike.gear);     } } 

Why does this give me the below error in the compiling process?

ShowBike.java:12: non-static variable this cannot be referenced from a static context         Bicycle bike = new Bicycle(5);                        ^ 
like image 895
mko Avatar asked Mar 11 '13 05:03

mko


People also ask

How do you fix non static variable this Cannot be referenced from a static context?

Therefore, this issue can be solved by addressing the variables with the object names. In short, we always need to create an object in order to refer to a non-static variable from a static context. Whenever a new instance is created, a new copy of all the non-static variables and methods are created.

What is non static variable Cannot be referenced from a static context?

Non-static Variable X Cannot be Referenced from a Static Context & Non-static Method X Cannot be Referenced from a Static Context. A static variable is initialized once, when its class is loaded into memory, and its value is shared among all instances of that class.

Can you access the non static variable in static context?

“Can a non-static method access a static variable or call a static method” is one of the frequently asked questions on static modifier in Java, the answer is, Yes, a non-static method can access a static variable or call a static method in Java.


1 Answers

Make ShowBike.Bicycle static.

public class ShowBike {      private static class Bicycle {         public int gear = 0;         public Bicycle(int v) {             gear = v;         }      }      public static void main() {         Bicycle bike = new Bicycle(5);         System.out.println(bike.gear);     } } 

In Java there are two types of nested classes: "Static nested class" and "Inner class". Without the static keyword it is an inner class and you will need an instance of ShowBike to access ShowBike.Bicycle:

ShowBike showBike = new ShowBike(); Bicycle bike = showBike.new Bicycle(5); 

Static nested classes and normal (non-nested) classes are almost the same in functionality, it's just different ways to group things. However, when using static nested classes, you cannot put definitions of them in separated files, which will lead to a single file containing a lot of class definitions.

like image 183
Alvin Wong Avatar answered Sep 17 '22 15:09

Alvin Wong