Let’s say I have 3 different classes:
Class Person,
Class Room,
Class House.
They are linked like this:
in class House I do: Room room = new Room();
in 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 class House?
The way I do it now is to repeat the method in class Room like:
public String getName(){
return person.getName();
}
So in House I call the getName() method from Room, and in Room I call the method getName() from Person. So the name-variable is then passed from Person via Room to House!
But this way I’m duplicating all methods from Person that I need to access in House. This can’t be right…. I thought about ‘extending’, but that doesn’t make sense.
Can someone please explain to me (I now have a lot of methods dupplicated in my code).
It may be basic OOP stuff, but I can’t seem to figure it out.
Thanks in advance!
You’re right. You don’t need to do that. That is not the correct way.
Since you are having a
Personreference inRoomclass, you just need to define a “getter” forperson: –And then form your
Houseclass, you can getpersonname and other details like this: –So, basically, you are getting a copy of
personreference (Not the copy of person instance itself) of yourroominstance, in yourHouseclass. And then using that reference, as if it were defined inHouseclass only.One more point, I saw that your getters are private. You should not do that. Make them public, else they won’t be accessible outside.
gettersandsettersshould almost always be public.