gpt4 book ai didi

java - 是否可以编辑抽象类? java

转载 作者:行者123 更新时间:2023-12-02 01:51:10 24 4
gpt4 key购买 nike

我有两个类。一个包含一堆不同类型的水果上的私有(private) HashMap (此类称为fruitStore),另一个是一个抽象类,在其字段中包含一个私有(private)字符串ArrayList(此类称为fruitNames)。

fruitStore中HashMap的键是每个水果的名称,该字段是水果的信息(价格和有效期等)。

目前,我的目标是将所有键(水果名称)放入 FruitNames 中的 ArrayList 中。

到目前为止,我尝试的是在fruitStore 中创建另一个私有(private)字符串数组,将其命名为名称,然后将所有名称存储在其中。之后,我决定在 FruitNames 类中创建一个函数来移入所有水果名称。

所以我在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
}
}

但是,我有一个问题。由于 ArrayList 名称是私有(private)的并且只能在 FruitStore 类中访问,因此我无法在任何其他类中使用它。我能想到的唯一解决方案是公开姓名,但我被告知不要这样做。

有人知道这个问题的解决方法吗?

最佳答案

您可以在fruitStore类中创建一个方法来为您获取大小,而无需暴露整个字段

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

关于java - 是否可以编辑抽象类? java ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52977151/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com