Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialJiten Mistry
4,698 PointsJava error
How would i get pass this error ?
./Example.java:6: error: non-static method getColor() cannot be referenced from a static context System.out.printf("%s", GoKart.getColor()); ^
public class Example {
public static void main(String[] args) {
System.out.println("We are going to create a GoKart");
GoKart goKart = new GoKart("red");
System.out.printf("%s", GoKart.getColor());
}
}
1 Answer
James Pamplona
10,015 PointsYou're trying to call the getColor()
method on the GoKart
class itself. Call the method on the goKart
instance (lowercase 'g').
System.out.printf("%s", goKart.getColor());
Jiten Mistry
4,698 PointsJiten Mistry
4,698 PointsThank you it worked, but could you explain why we use lower case?
James Pamplona
10,015 PointsJames Pamplona
10,015 PointsSure. It's about Classes vs objects (also referred to as instances). In Java, and in many other programming languages as well, it's a common convention to name classes beginning with uppercase to help us differentiate them from variables, which typically begin with lowercase .
GoKart
is the name of the class, the "blueprint," from which any number of concrete instances can be made.In the second to last line in your code above...
GoKart goKart = new GoKart("red");
...we are creating an instance variable named
goKart
(though we could call it anything such asmyKart
if we wanted) which is then a fully functioning, "live," instance of theGoKart
class. Then in the last line, we are calling thegetColor()
method on that instance.The course on Java Objects should elaborate on this more as you go on, but let me know if you're still having trouble.
Good luck!