Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to use an object that is created already as an argument in java

I have an AddressBook class and a Persons class in my program. The AddressBook class has an array of Persons object.

import java.util.*;
public class Persons {
    private String name;
    private String lastName;
    private String addres;
    private String city;
    private String state;
    private int zip;
    private String phoneNumber;

    public Persons(String name , String lastname,String phoneNumber) {
        this.name = name;
        this.lastName = lastname;
        this.phoneNumber = phoneNumber;
    }

//some getter and setter here for all private fields and some other code

and this is the AddressBook.addPerson method:

public void addPerson(Persons prs) {
    for (int i = 0; i < ArrayOfPerson.length; i++) {
        if (ArrayOfPerson[i] == null) {
            ArrayOfPerson[i] = prs;
            break;
        }
    }
}

and the Main class :

public class Main {        
    public static void main(String[] args) {
        AddressBook addr = new AddressBook();
        addr.addPerson(new Persons("first name", "first lastname", "123"));// in here for example/ how can i use this person object later
        addr.addPerson(new Persons("second name", "second lastname", "456"));
        addr.addPerson(new Persons("third name", "thirs last name", "789"));
        addr.addPerson(new Persons("fourth name", "fourth last name", "101112"));
    }
}

My question regards the Main class. How can I re-use the created persons object? For example, I would want to do something like this :

System.out.println(x.getname());

where x is a person object that is created by new keyword as a argument.

Excuse me if my question is that of a beginner ... I searched in google and found nothing.

like image 215
amir_70 Avatar asked Dec 25 '22 15:12

amir_70


1 Answers

You just need to assign this object to a variable while creating it then you can access it and pass it as parameter :

Persons firstOne = new Persons("first name","first lastname","123");

And your code will be:

public static void main(String[] args) {
    AddressBook addr = new AddressBook();
    Persons firstOne = new Persons("first name","first lastname","123");

    //You will use it as parameter like this:
    addr.addPerson(firstOne);
    addr.addPerson(new Persons("second name", "second lastname","456"));
    addr.addPerson(new Persons("third name", "thirs last name","789"));
    addr.addPerson(new Persons("fourth name", "fourth last name","101112"));
}

Then you can access it like this:

System.out.println(firstOne.getname());

Or without creating a variable you can get it from the collection by its index addr.get(index) :

System.out.println(addr.get(0).getname());
like image 65
cнŝdk Avatar answered Apr 27 '23 22:04

cнŝdk