说我有一个方法backup()
的超类,该方法备份实例变量cardlist
中的所有对象。我把那个类子类化。我想使用已经在此处编写的相同功能,但希望它能作用于list
的子类版本。
在子类中,我只是这样写的:
@Override
public void backUpFlashCards() throws IOException {
super.backupFlashCards(currentCards);
}
在超类中调用此方法:
public void backupFlashCards(ArrayList<Card> cards) throws IOException{
CARDS = cards;
backUpFlashCards();
}
...所以我基本上将instace变量设置为我希望它在超类中。似乎倒退(或倒挂)。这是应该做的方式吗?如果我删除了覆盖,然后又在子类上调用了其他方法,该代码将多态地称为超类方法,那么我如何让超类引用正确的实例变量?我在这里有什么问题,是否有一般解决方案?
编辑:
public class Database implements FlashCardProvider {
protected String DBURL = "jdbc:mysql://localhost:3306/FlashCardShark?useUnicode=true&useSSl=false&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC";
protected String pw = "Basketball12";
protected String user = "root";
private ArrayList<Card> CARDS = new ArrayList<>();
@Override
public void backUpFlashCards() throws IOException {
int counter = 1;
Date today = new Date();
DateFormat df = DateFormat.getInstance();
String todayFile = df.format(today).replaceAll(" ", "-");
String todayFile1 = todayFile.replaceAll("/", "-");
Path p1 = Paths.get("/home/maxbisesi/FlashCardShark/FlashCards/", todayFile1 + ".txt");
Files.createFile(p1);
System.out.println(p1);
BufferedWriter bw = new BufferedWriter(new FileWriter(p1.toFile()));
// make sure you close this BufferedWriter
ArrayList<Card> cards = CARDS;
try {
bw.write(df.format(today));
bw.newLine();
bw.write("Flash Cards \n");
bw.newLine();
for (Card c : cards) {
bw.write("================================================\n");
bw.write("-" + counter + "-\n");
bw.write("================================================\n");
bw.write(c.getCard());
bw.newLine();
bw.write("================================================\n");
bw.write(c.getAnswer());
bw.newLine();
bw.write(c.getCategory());
bw.write("================================================\n");
counter++;
}
bw.close();
} catch (IOException e) {
System.out.println("Problem saving cards");
e.printStackTrace();
}
}
}
public interface FlashCardProvider {
void addFlashCard(Card c);
ArrayList<Card> pullCards();
void updateRatings(ArrayList<Card> cards);
void updateFlashCard(Card newCard);
void backUpFlashCards() throws IOException;
Card searchByID(int id);
ArrayList<Card> searchByCategory(String cat);
String[] getAllCategories();
ArrayList<Card> findKeywords(String word);
}
public class LearnOrDieDAO extends Database {
private ArrayList<Card> currentCards = new ArrayList<>();
@Override
public void backUpFlashCards() throws IOException {
...
}
}
我想也许子类可以只将所有卡片存储在超类列表中。
我的基本问题是:如果您想扩展一个类,该怎么做,这样就不必重写功能来使用子类实例变量,或者您必须这样做错了吗?