can anyone explain to me, why i am not allowed to do the following?
public class first_class {
int grade1=7;
int grade2=4;
double average;
public double calcAverage() {
average=(grade1+grade2) / (2);
System.out.println(average);
return average;
}
public static void main(String []args) {
first_class.calcAverage();
}
}
I get the error message “non-static method calcAverage() cannot be referenced from a static context at first_class.main(first_class.java:17)”.
Try this instead:
What this does is first create a new instance of your first_class class, then calls the
calcAverage()method on that instance. Now, you are making a reference to the method on the instance, as opposed to trying to reference it statically.The error is an indication that from something static (the main() method) you tried to refer to a method without an instance. You can do this if the method is marked static, but your calcAverage() is not marked static, so you need to create an instance instead.