0

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.

Luke_Nuke
  • 461
  • 2
  • 6
  • 23

1 Answers1

1

We use this to refer to current object that is class object itself. In your case id is not a class variable but a static variable. Hence you can not access a static variable with class object reference this.

Abhijit Pritam Dutta
  • 5,521
  • 2
  • 11
  • 17