简体   繁体   中英

How to access an object's state without passing as parameter in method?

I am writing a program for a college class that manages inventory, like through adding, removing, and renting items like DVD Players, furniture, and TV sets. My problem is, I want to get an object's saved state without passing in the object as an argument into the method to retrieve its state.

ABCRentals.java

private List<Integer> idNumbers = new ArrayList<Integer>();
private List<Item> items = new ArrayList<Item>();
public String[] itemTypes2;

public boolean add(Item item)
{
    if (items.size() >= 300)
        return false;
    else
    {
        idNumbers.add(idNumbers.size() + 1);
        items.add(item);
        return true;
        // Code that adds item to itemTypes2 array (removed to avoid unnecessary code dump)
    }
}

public String[] getItemArray() {
   return itemTypes2;
}

DVDPlayer.java

public int getId(ABCRentals abc)
{
    String[] itemArray = abc.getItemArray();
    int id = Arrays.asList(itemArray).indexOf("DVDPlayer #" + Integer.toString(ID)) + 1;
    return id;
}

Driver.java

public static void main(String[] args)
{
    ABCRentals abc = new ABCRentals();
    DVDPlayer item1 = new DVDPlayer();
    boolean flag = abc.add(item1);      
    int id = item4.getId(abc);
    System.out.println("Id: " + id);
}

Basically what I mean is, when I call the getId() method in the Driver class, I can't pass in the abc object as a parameter in order to get its state, as my professor requires me to have certain method signatures, with getId() in particular required to accept zero arguments. The abc object's state is changed when implementing the add() method and adding in an item. So, if I were to create a new instance of ABCRentals inside the getId() method, it would have an empty state as there'd be no items added in the object. Is there any way I can implicitly retrieve the abc object without passing it as a parameter? My code above works, but my method signature cannot be the way it is.

DVDPlayer.java
    private ABCRentals mAbc;

    public void init(ABCRentals abc){
      mAbc = abc;
    }

call this init method to initialize your class instead and then call getId method.

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