0

In class Browser I have the field

   private ArrayList<WineCase> basket; 

and also I have created the ArrayList within the constructor:

   basket = new ArrayList<WineCase>();

In class Website I have to access this ArrayList. When I try to compile this for-each header:

 for(WineCase wineCase : basket) 

the error is that "variable basket is not declared". How to declare the ArrayList from Browser class ?

2
  • You need to pass it as a parameter somewhere. You can then store it in a private field. Commented Dec 3, 2013 at 18:08
  • I think you sohuld make the ArrayList static, and Public. As well to access it you should use Browser.basket or something. Even though this way is a little unprofessional, it may work. Commented Dec 3, 2013 at 18:10

2 Answers 2

1

You've declared basket as private in Browser, so you can't access it directly. That's good; it's encapsulated.

Create a "getter" method in Browser to access it:

public ArrayList<WineCase> getWineCases() {
    return basket;
}

Of course, you'll still need an instance of a Browser on which to call getWineCase. Then you can just call the method:

for(WineCase wineCase : aBrowser.getWineCases()) 
Sign up to request clarification or add additional context in comments.

Comments

1

You can't access private instance variable belong to another class. You need to declare the basket in Website class or, make the basket as a public instance variable (not recommanded, better to access through a getter method), and access it with an instance of Browser class from Website class.

pulic ArrayList<WineCase> basket; //in Browser class

or

private ArrayList<WineCase> basket; //in Browser class

public ArrayList<WineCase> getBasket() {} // in Browser class

and

for(WineCase wineCase : browserInstance.basket) // in Website class

1 Comment

Or create a getter method in class Browser that returns basket.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.