Accessing variables from multiple classes in Java
Let's say I have 3 different classes:
The class of the Person , Class Room , Cool house .
They are related as follows:
in the class House I do: Room room = new Room();
in the class Room I do:Person person = new Person();
In Person, I have this method:
public String getName(){
return name;
}
How can I access this method from the House class ?
Now I have to repeat the method in the Room class , for example:
public String getName(){
return person.getName();
}
So in House I call a method getName()
from Room , and in Room I call a method getName()
from Person . Thus, the variable name is then passed from Person through Room to House !
But this way I duplicate all the methods from Person that I need to access House. This may not be right ... I was thinking about "expanding", but it doesn't make sense. Can someone please explain to me (I now have a lot of methods duplicated in my code). This may be basic OOP stuff, but I can't seem to figure it out.
Thanks in advance!
source to share
But in this way I duplicate all the methods from the Person that I need access to the house. It can't be right ....
You're right. You don't need to do this. This is not the right way.
Since you have a reference Person
in the class Room
, you just need to define a "getter" for Person
: -
public Person getPerson() {
return person;
}
And then shape your class House
, you can get the name Person
and other data like: -
room.getPerson().getName();
room.getPerson().getAge();
So basically you get a Person
help copy (not a face instance) of your instance Room
in your class House
. And then using that reference as if it were only defined in the class House
.
Another point, I saw that your recipients are private. You shouldn't be doing this. Make them public or they won't be available on the street. getters
and setters
should almost always be public.
source to share