Mike Z Mike Z - 2 months ago 6
Java Question

error: non-static method eatTreats() cannot be referenced from a static context

I have read many of the other questions on this error and the dots are just not connecting in my head.

I have three methods in a separate class and they are :

public class MyDog {
private int treatCount;

public static void woof(int numberOfBarks) {
if(numberOfBarks > 0){
System.out.print("Woof ");
woof(numberOfBarks-1);
}
}
public void eatTreats () {
treatCount++;
}
public int howManyTreats() {
return treatCount;
}


}

I have my main class accessing this method like such

public int mydogrun () {
MyDog ValDog = new MyDog ();
//create new instance of MyDog
MyDog.woof (5);
MyDog.eatTreats();
MyDog.eatTreats();
MyDog.eatTreats();
MyDog.howManyTreats();
}


And when I try to compile I am getting : error: non-static method eatTreats() cannot be referenced from a static context" and "error: non-static method howManyTreats() cannot be referenced from a static context"

I am not sure where the static is coming from. I do not see the static word anywhere in there so I

Answer

Its because method is not defined as static and you are calling method in static manner.

Mark method as static or use MyDog object to call methods.

public int mydogrun () {
    MyDog valDog = new MyDog ();
    //create new instance of MyDog
    MyDog.woof (5);
    valDog.eatTreats();
    valDog.eatTreats();
    valDog.eatTreats();
    valDog.howManyTreats();
    //return some integer
}

PS: - Ideally your class object refernce variable must be in small characters as per java conventions.

Comments