java - 将需要的变量发送到子类方法 - 作为方法属性或作为 protected 类属性

标签 java inheritance


所以我的问题是我不知道这方面的最佳做法。我有一个具有以下内容的抽象父类(super class):

protected ArrayList<Item> itemList; 
protected abstract ArrayList<Item> getSpecificObjects(SQLiteStatement st);
public ArrayList<Item> getItems() {
            itemList= new ArrayList<Item>();
            SQLiteStatement st = generateStatement();
            getSpecificObjects(st);
            return itemList;
        }

getSpecificObjects(st)是在该类中声明的抽象方法,其实现在抽象类的子类中。它接收一个 SQLiteStatement 局部变量作为方法变量,并将需要的数据写入实例保护变量 itemList

我是否也应该将 itemList 作为局部变量发送,而不是将其设为实例变量?或者我应该更好地使 SQLiteStatement 以及实例保护变量?

代码以任何一种方式工作,但我只是不知道什么是最好的。
感谢您的帮助!

最佳答案

Should I send itemList as a local variable as well instead of making it an instance variable? Or better should I make the SQLiteStatement as well a instance protected variable?

这真是一个生命周期的例子。如果这些值需要在方法调用后保持不变,那么您应该将它们设为实例值。如果它们不存在,并且应该在方法完成后丢弃,则在方法 header 中声明它们,以便 GC 可以处理它们。

关于java - 将需要的变量发送到子类方法 - 作为方法属性或作为 protected 类属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18308565/

相关文章:

java - 仅从测试套件运行 Junit 测试用例,而不是单个类

C# 继承 : casting of parent object to child

java - 哪个先执行,父构造函数还是子构造函数?

java - 对 Future.get() block 的方法调用。这真的很可取吗?

c# - 成员声明中 "new"的确切含义

C++:继承和运算符重载

c++ - 一个继承类可以有多少个构造函数?

java - spring中条件注解的排序评估

java - 斯科布勒。 onAnnotationSelected 未调用,当我设置自己的注释时

java - 返回 x param 匿名对象