User9123
User9123

Reputation: 774

Is it possible to edit an Abstract class? Java

I have 2 classes. One which contains a private hash map on a bunch of different types of fruit (this class is called fruitStore), and the other which is an abstract class which contains a private ArrayList of string in its field(this class is called fruitNames).

The key to the HashMap in the fruitStore is the name of each fruit, the field is information on the fruit (price and expiry date etc.).

For now, my goal is to put all the keys (fruit names) into the ArrayList in fruitNames.

What I have tried so far is creating another private string array in fruitStore calling it names, then storing all the names in there. After that I decided to make a function in the fruitNames class to move in all the fruit names.

So I made the following code in fruitNames

//making an object of fruit_store
private fruitStore fruit_store = new fruitStore();

void insert_fruit(ArrayList<String> fruits){
    for ( int i = 0; i < fruit_store.names.size(); i++ ){
    //here i planned to add the elements in names to the fruitList array
    }
}

However, I have a problem. Since the ArrayList names is private and only accessible in the fruitStore class, I am unable to use it in any other class. My only solution I can think of is to make names public, however I was told not to do that.

Would anyone know a workaround to this problem?

Upvotes: 0

Views: 490

Answers (2)

Ryan Walden
Ryan Walden

Reputation: 167

It sounds like you would be much better off declaring it as Protected.

"The private modifier specifies that the member can only be accessed in its own class. The protected modifier specifies that the member can only be accessed within its own package (as with package-private) and, in addition, by a subclass of its class in another package." - Controlling Access to Members of a Class

Upvotes: 1

Neo
Neo

Reputation: 79

You can make a method in the fruitStore class that gets the size for you without exposing the entire field

public int getSize(){
    return names.size()
}

Upvotes: 1

Related Questions