-3

So, i'm new to coding and am working on an exercise with this code.

What I'm wondering is what "nextRoom = currentRoom.northExit;" etc does as in my eyes the dot notation should be used as object.method(parameters) as opposed to object1.object2 ?

class Room

private String description;
private Room northExit;
private Room southExit;
private Room eastExit;
private Room westExit;

class Game

private Room currentRoom;

private void move(String direction)
{

Room nextRoom = null;

    if(direction.equals("north")) {
        nextRoom = currentRoom.northExit;
    }
}

Thanks in advance !

UserC4
  • 13
  • 1
  • 1
    Why do you think a `.` should only be used to access methods? What's the point for that limitation? – Tom Aug 13 '17 at 12:37
  • I can't decipher what exactly you don't understand. What do you think an object is and what to you think `.` does? – Oleg Aug 13 '17 at 12:37
  • It's just that we haven't seen another use for a " . " other than to access methods so it's strange that they use such an example before explaining it. – UserC4 Aug 13 '17 at 12:40

3 Answers3

0

You can use dot notation to access fields of an object, not only methods. However in this case that expression is invalid, because you cannot access private members of the class Room, outside the class. And since northExit is a private member of class Room, it can only be accessed inside the class Room only. You could access the private members only through get methods. If class Room were

private String description;
public Room northExit;
public Room southExit;
public Room eastExit;
public Room westExit;

you would be able to use the dot notation to access northExit.

kkica
  • 4,034
  • 1
  • 20
  • 40
  • Technically speaking, in Java these are not *properties* but *fields*. – Roman Puchkovskiy Aug 13 '17 at 12:38
  • Edited it. Thank you, for your input. – kkica Aug 13 '17 at 12:39
  • Thanks a lot to help me out ! – UserC4 Aug 13 '17 at 12:55
  • 1
    You are welcome! I see that you are new here. Whenever you see an answer that helps you understand or solves your problem, it is a good idea to up the answer or accept it(you can accept only if is to your own question). This way, others who might see the question, would know that that answer is helpful and they read it. This way, you can help them too, which is the purpose of stack sites. – kkica Aug 13 '17 at 13:11
0

Well seems like what you're looking for is details of Object Creation which is :

private Room currentRoom;

and further more in the context

currentRoom.northExit;

Using an Object created of a class.

Naman
  • 27,789
  • 26
  • 218
  • 353
0

It doesn't have to be methods only, you can call properties (obj1.propertyName) to get its value. and here you assign nextRoom property to the the value of the northExit property in the currentRoom Object.

Adel
  • 23
  • 7