Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

accessing variables among multiple classes in Java

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!

like image 921
pbc278 Avatar asked Jul 26 '26 11:07

pbc278


2 Answers

But this way I'm duplicating all methods from Person that I need to access in House. This can't be right....

You're right. You don't need to do that. That is not the correct way.

Since you are having a Person reference in Room class, you just need to define a "getter" for person: -

public Person getPerson() {
    return person;
}

And then form your House class, you can get person name and other details like this: -

room.getPerson().getName();
room.getPerson().getAge();

So, basically, you are getting a copy of person reference (Not the copy of person instance itself) of your room instance, in your House class. And then using that reference, as if it were defined in House class 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. getters and setters should almost always be public.

like image 122
Rohit Jain Avatar answered Jul 29 '26 03:07

Rohit Jain


Expose person as a property of Room.

What you have is a bit weird because one would expect room.getName() to return the room's name.

Instead Room should have a getPerson() method so when a person name is needed, room.getPerson().getName()

like image 26
Taylor Avatar answered Jul 29 '26 04:07

Taylor



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!