I've began learning Java yesterday with the book Head First Java.
Now im at the GuessGame Example and I dont fully understand it...
First of all here is the code:
What i dont understand is:
I know these are instance variables, but i do not know what instance variables are
I've tried to find out and all I know is that they represent the state of the object. I dont really understand what that is (maybe because, as you may already have noticed, english isnt my primary language)
So could someone explain how they work/what they are for?
if you were going to have a real game with real people, you could make three nametags that say "Player1", "Player2" and "Player3". When your guests arrive, you would assign a nametag to a specific person.
That's really all we're doing here.
Lines 2-4 in your code is you creating the nametags with those labels - but they don't represent a real thing yet. We just know we (might) use them later.
Then, on lines 7-9, you create a Player object, and assign the nametag to them, one at a time.
An instance variable means that whenever the object is created, you will have a variable called that. So, somewhere, there is code that creates a Player. That class might have an instance variable of type String, that holds a name. You could then refer to p1.name, p2.name or p3.name to get each person's name.
Does that help?
There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
Java is object-oriented, so you need to start thinking about the objects involved.
Of course you could easily write it as one class if you wanted to, but writing it as 3 is easier and more flexible, when you get used to it.
Lines 2-4 that you mention declare the Player variables. In this case, it would work if you declared them in the startGame method, but only because there's only this method in the class. The Players are instance variables belonging to any instance of the GuessGame class. If you declared it within the method, they would be local variables to that method.