I keep having this issue whenever I write a class where when I try to initialize an object belonging to that class like so
class name = new class();
I keep receiving the error “non-static variable this cannot be referenced from a static context”
For example with this simple class
public class num
{
private int num;
public num(int num)
{
this.num = num;
}
public int getNum()
{
return num;
}
}
public static void main(String[] args)
{
num x = new num(10);
System.out.println(x.getNum());
}
I realize simply adding static before the class keyword at line 1 would solve the issue but I would like to know why would I need to do that? Is it an error in my code or just a general requirement when writing classes?
nnmk1 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.