I encountered an error and I am really confused. I have following code (very simple just for practice the idea is each new object has ID incrmented also I want be able to edit current ID in the class at any moment):
public class Main
{
public static void main(String[] args) {
Klient pierwszy = new Klient();
System.out.println(pierwszy.id);
Klient drugi = new Klient();
System.out.println(drugi.id);
System.out.println(Klient.id);
Klient.setId(100);
System.out.println(Klient.id);
}
}
class Klient {
static int id = 0;
Klient() {
id++;
System.out.println(id);
}
static int setId(int id1) {
id = id1;
return id;
}
}
The issue is in the method in the class Client in following form it works just fine. But when previously there was:
static int setId(int id) {
this.id = id;
return id;
}
The compiler was throwing an error: Non-static variable cannot be referenced from a static context pointing to this.id = id; If I change parameter name to be different from id so I don't have to use this.id, error is gone. I am totally confused.