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

旧城冷巷雨未停 提交于 2019-12-05 13:51:42
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();

When a person is an aggregation of address, contact informations and so on, you should have getters and setters for those. You'd then write this to set street on a person:

person.getAddress().setStreet("this and that")

and you could also assign a new address whatsoever:

person.setAddress(new Address("streeetname", "cityname"))

This is a common idiom in Java and the way to go. Having public access objects creates new problems since this kind of access cannot be changed without side-effects in all classes using them.

What I see here is a dependency inversion issue. Your class Person depends on Address and Contact. In the purest sense the Address and Contact should be Interfaces, so their implementations could be swapped out at runtime.

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

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

  public Address getAddress() {
    return this.address;
  }

  public setAddress(Address address) {
    this.address = address;
  }

  public Contact getContact() {
    return this.contact;
  }

  public setContact(Contact contact) {
    this.contact = contact;
  }

}

Then you could access Address in the following way:

person.get(1).getAddress().setStreet("place");
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!