Search code examples
javaapacheoopinheritancedelegation

How can I extend the functionality of apache FTPFile?


I'm learning OOP in Java and I've come across a problem. I need to create a custom object Folder that retains the functionality of the FTPFile object and add some more to it.

FTPClient client = new FTPClient();
FTPFile[] folders = client.listFiles();

I need to convert all the objects in the array folders from FTPFile into Folder objects and I thought about setting the state of the superclass inside the constructor of the subclass:

public Folder(FTPFile ftpF) {
    super.setName(ftpF.getName());
    super.setLink(ftpF.getLink());
    super.setHardLinkCount(ftpF.getHardLinkCount());
    super.setGroup(ftpF.getGroup());
    super.setSize(ftpF.getSize());
    super.setTimestamp(ftpF.getTimestamp());
    super.setType(ftpF.getType());
    super.setUser(ftpF.getUser());
}

But I don't know if this is a good practice. Should I go with this or should I store a FTPFile object in the state of a Folder object and call its functionality whenever I need it?


Solution

  • Delegation

    or should I store an FTPFile object in the state of a Folder object and call its functionality whenever I need it?

    You came across the idea of delegation. This is a very flexible way of extending functionality of a class without to inherit it.

    Example

    class Folder {
        private FTPFile ftpFile;
    
        public FTPFile(FTPFile ftpFile) {
            this.ftpFile = ftpFile;
        }
        
        // more code..
    }
    

    Let's imagine you want to extend the method setName(string) of FTPFile and all name should be uppercase:

    public void setName(String name) {
        String uppercaseName = name.toUppercase();
        
        // delegate the task with the uppercase name
        ftpFile.setName(uppercaseName);
    }