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 trial

Java The Challenge

Brendan Passey
Brendan Passey
999 Points

non-static method getCowName() cannot be referenced from a static context

I am trying to call Cow.getCowName() from Main.java (within the main method). and get this error. Here's Cow.java

class Cow { private final String name;

public Cow (String name) { this.name = name; }

public String getCowName() { return name; } }

Here's Main.java import java.io.Console; public class Main {

public static void main(String[] args) { Console console = System.console();

Cow cow = new Cow("Larry");

System.out.printf("The new Cow's name is %s",
                  Cow.getCowName());
  }

} I googled it and got this answer - A non-static method is dependent on the object. It is recognized by the program once the object is created. But a static method can be called before the object creation. Hence you cannot make the reference.

Which I get the gist of but what constitutes calling a method from a non static context? How do I fix my code so I am not doing that? The only thing I can think of is that it's within the main method which is indeed static but I called a bunch of methods precicely like this in the hangman project and got no problems.

Can someone clarify this for me please?

3 Answers

Steven Parker
Steven Parker
231,271 Points

Non-static methods are called on an instance, where static methods are called on the class itself. You created an instance named "cow" (little "c"), but attempted to call the method on the class "Cow" (capital "C").

Just fix the spelling:

                  cow.getCowName());
Brendan Passey
Brendan Passey
999 Points

Doh, yep now I see it I feel silly. Thanks Steven.

Nikola Vichev
Nikola Vichev
1,668 Points

Hi, guys, I keep getting this error ...help, please

import java.io.Console;

public class Main {

public static void main(String[] args) { Console console = System.console();

Cow cow = new Cow("Larry");

System.out.printf("The cow's name is %s,
                  cow.getCowName());

} }

Main.java:11: error: illegal start of expression
cow.getCowName());
^
Main.java:11: error: ';' expected
cow.getCowName());

Aaron Choe
Aaron Choe
1,505 Points

Hey Nikola, you're forgetting a quotation mark :)