简体   繁体   中英

How to reference to another object in Java?

I'm doing an homework question, and not sure what is wrong with my code. The question is: http://prntscr.com/1xe4gd .

My code so far:

public class Person //This is the class
{
    String firstName;
    String familyName;
    boolean isFemale;
    String partner;
}

My method so far is:

Person getAngelinaJolie()
    {
        Person person1 = new Person();
        person1.firstName = "Angelina";
        person1.familyName = "Jolie";
        person1.isFemale = false;
        person1.partner.firstName = "Brad";
        person1.partner.familyName = "Pitt";
        return person1;
    }

When I compile, error says "cannot find symbol - variable firstName". Could anyone please help me with this. Not sure why it cant find the symbol.

You have defined String partner; in class Person, but I suppose you mean Person partner; then you will be able to set it's properties after person1.partner = new Person(); of course

here is the proper code:

Person getAngelinaJolie()
    {
        Person person1 = new Person();
        person1.firstName = "Angelina";
        person1.familyName = "Jolie";
        person1.isFemale = true;

        person1.partner = new Person();
        person1.partner.firstName = "Brad";
        person1.partner.familyName = "Pitt";
        person1.partner.isFemale = false;

        person1.partner.partner = person1;

        return person1;
    }
public class Person //This is the class
{
    String firstName;
    String familyName;
    boolean isFemale;
    Person partner;
}

and the same method now

Person getAngelinaJolie()
    {
        Person person1 = new Person();
        person1.firstName = "Angelina";
        person1.familyName = "Jolie";
        person1.isFemale = false;
        person1.partner.firstName = "Brad";
        person1.partner.familyName = "Pitt";
        return person1;
    }

now person.partner.firstname will refer to the already defined Person partner in Person

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM