+ 1

Error "Non-static variable"

Hey I have been following along the java tutorial, and I ran into an error I cannot understand, or google my way to a solution. [code]"MyClass.java:10: error: non-static variable this cannot be referenced from a static context Animal dog = new Animal(); ^ MyClass.java:13: error: non-static variable this cannot be referenced from a static context vehicle v1 = new vehicle(); ^ MyClass.java:14: error: non-static variable this cannot be referenced from a static context vehicle v2 = new vehicle();"[/code] I got this error after I added the new "class vehicle" the other classes, never complied with errors, what am I missing? My code: [code]public class MyClass{ public static void main(String[] args){ int x = sum(5,2); System.out.println(x); Animal dog = new Animal(); dog.bark(); vehicle v1 = new vehicle; vehicle v2 = new vehicle; v1.color = "red"; v2.horn(); } // end of main method. static int sum(int val1, int val2){ return val1 + val2; }// end of sum() class Animal { void bark(){ System.out.println("Woof,Woof!"); } } // End of Animal public class vehicle { int maxSpeed; int wheels; String color; double fuelCapacity; void horn() { System.out.println("Beeep!"); } } // end of vehicle class. } // end of Main class MyClass [/code] By the way I used a notepad and cmd promp following along the java tutorial.

27th Sep 2017, 10:45 AM
Steven
Steven - avatar
2 Answers
+ 2
The issue here is that all of your separate classes are actually inner classes of your main class. Try separating each class completely. public class myClass{ // stuff in here }// end main class class Animal{ }// end animal class vehicle{ } // end vehicle *Notice that you ended the main class after the vehicle class, so the vehicle and Animal classes are inside the main class.* You also forgot parenthesis after creating your vehicles. Change: "vehicle v1 = new vehicle;" To: "vehicle v1 = new vehicle();" (Then do the same thing for v2)
27th Sep 2017, 3:54 PM
Rrestoring faith
Rrestoring faith - avatar
0
ah okay, thank you for the reply i will try it as soon as i get acess to my pc 🙂
28th Sep 2017, 6:05 PM
Steven
Steven - avatar