Abstract method Overriding, implementing another type of return in java

I have an abstract Java class FileManagerthat contains three methods for file operations.

  • openFile()
  • abstract readFile()
  • closeFile()

    I want to specify all three methods inside a class FileManager. However, the method readFile()will need to read different types of files. namely csv, xls, doc. In the future, code may even read PDFfiles.

The return type for all such calls will be different.

This means that when I read the csv file, I will return an ArrayList, on the other hand, the xls file will return a HashMap, etc.

To accomplish this and make the factory code compatible, I plan to make a separate reader class in the project for each file type. ( CSVFileReader, DOCFileReader, XLSFileReaderEtc.)

Is there a way when I can get a developer to include a method readFile()in his implementation of ______ (CSV / XLS / DOC) Filereader?

PS: Java determines that an overridden method in a subclass must have the same or subtype of return type. My question is how to specify readFile()in the implementation FileManagerand also have a different return type for each of the different file types?

+4
source share
2 answers

Just use the versatility:

public abstract class FileManager<OUPUT> {
    public abstract OUTPUT readFile();
}

public class CSVFileReader extends FileManager<List<String>> {
    @Override
    public List<String> readFile() {
        // ...
    }
}

public class XLSFileReader extends FileManager<Map<String, String>> {
    @Override
    public Map<String, String> readFile() {
        // ...
    }
}
0
source

You would like to use as the return type. This will allow you to choose the type of return on the fly.

public <T> T mymethod(T type)
{
  return type;
}

Java Oracle. https://docs.oracle.com/javase/tutorial/java/generics/types.html

+1

Source: https://habr.com/ru/post/1607082/


All Articles