Is it a bad idea to sub-class java.io.File?

234 Views Asked by At

I am having a debate with another developer who dislikes my idea of sub-classing java.io.File for our custom needs (such as, for example, having an AWSFile, or GoogleCloudStorageFile, (for the sake of argument), where we would need to override some of the methods like listFiles(), getAbsoluteFile, etc.). When is it okay to sub-class java.io.File?

Why is there, for example, no generic interface for this, which java.io.File could be implementing, so that it would be more generic? Was this done so on purpose?

I would like to understand whether, or not my approach is indeed good, or bad, as I've seen it in other API-s before (if I recall correctly, I'd seen the same approach in TrueZip a while ago).

The purpose of this question is not to start a flame war, or anything, but to get an examples of how to implement different types of File entities (AWSFile, JDBCFile, etc.) and potentially get a meaningful list of pros and cons.

2

There are 2 best solutions below

5
karthik On

Subclasses will be tightly coupled to superclasses, your code would be weak. You must try delegation before inheritance if possible.

public class YourFileWrapper {

private File yourFile;


public File getYourFile() {
    return yourFile;
} 
//rest of your code
1
Tschallacka On

My personal preference would be that you make an interface RemoteFile and you implement there the methods you need for the remote files.

In it I would suggest you put all the method types you will need for remote getting and setting file.

public interface RemoteFile {
    public File getLocalFile();
    public String getRemotePath();
    public boolean isDirectory();
    public List<RemoteFile> listFiles();
    ... etc...
}