Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is there a way to access an object within an object?

I'm practicing java by building a simple directory. I have 4 Classes. These are:

  1. Person

  2. Address

  3. Contact

  4. testClass

I have already finished creating this system and it works the way I want it. I did this by making 3 different arrays for the Person, Address and Contact. To link the Person, Address and Contact together I place them on there respective array with the same index number. (Not literally linking them together, just a way to know which address or contact to access when editing a person).

But now, I want to optimize it. I want to create a single HashMap to hold a person with the address and contacts within it. Please see my code below for more information.

Person.class

public class Person {
private long Id;
private firtName;
private Address address;
private Contact contact;

//some setter and getter methods

public Person(Address address, Contact contact) {
this.address = address;
this.contact = contact;
}
}

Address.class

public class Address {

private String street;
private String city;
private String province;


//some setter and getter methods
}

Contact.class

public class Contact {

private long Phone;
private String Email;

//some setter and getter methods
}

testClass.class

public class testClass {

public static void main(String[] args) {
HashMap<Integer, Person> person = new HashMap<Integer, Person>();

person.put(1, new Person(new Address(), new Contact)));
person.get(1).setStreet("place");

}

}

My question is, on this line of code in the testClass

person.get(1).setStreet("place");

is there a way to directly access/edit the person's address or contact without creating a separate array or method?

like image 614
bryn Avatar asked Jan 06 '23 22:01

bryn


1 Answers

private Address address;
private Contact contact;

If you were to make these public instead of private you would be able to access them directly like so:

Person person = new Person(new Address(), new Contact());

Person p = person.get(1);
String city = p.address.getCity();
String email = p.contact.getEmail();

However this violates the principle of encapsulation (you should hide your inner fields and allow access only through methods).

Instead you should create your person class as follows:

public class Person {
    private long Id;
    private firtName;
    private Address address;
    private Contact contact;

//some setter and getter methods

    public Person(Address address, Contact contact) {
        this.address = address;
        this.contact = contact;
    }

    public Address getAddress() {
        return address;
    }

    public Contact getContact() {
        return contact;
    }
}

and access through

Person p = person.get(1);
String city = p.getAddress().getCity();
String email = p.getContact().getEmail();
like image 106
14 revs, 12 users 16% Avatar answered Jan 17 '23 18:01

14 revs, 12 users 16%