sorry if this is a duplicate question, but I'm getting kind of desperate to solve a problem for a school project (due date tomorrow). I'm very new to Java and this project involves storing data from certain objects to a local repository and also reading the data from the repo. The repository handler class is in one package and the objects are in another.
My problem is that I don't know how to make generic methods in the handler to be able to read and write any object that extends X.
For example, let's say I have Fruit.
Apple extends Fruit. Orange extends Fruit.
Both have their own unique attributes that I need to write/read to/from a file.
I wanted to have a method like ArrayList repo_reader(String filepath) That reads from a file and returns Apples and Oranges.
The only way that I know how to do this is having a field in the file stating which type of fruit it is, reading it and throwing it to a switch case like
switch (fruit_type){ case "Orange": Orange orange = new Orange(); orange.setOrangeSpecificAttribute("ble"); FruitBasket.add(orange); case "Apple": Apple apple = new Apple(); apple.setAppleSpecificAttribute("bla"); FruitBasket.add(apple);
But then the method wouldn't be generic. Everytime that someone creates a new Fruit class, they would have to also change the repo_handler methods accordingly. The same would also happen with the writing method.
I could have the Fruit classes all implement their own method to write and read, but I don't want that. I want repo_handler class to deal with all the file reading and writing.
Again, sorry if it's a stupid question, and thanks for your guys' attention!
Btw, it's a CSV file, forgot to mention.