Search code examples
javastringabstractsuperclass

Java abstract variable (superclass use subclass's String)


I have an abstract class Loader:

public abstract class Loader
{
    private String EXTENSION = ".xxx";
    private String dir;

    public abstract Object load(String file);
    public abstract List<?> loadList(String file, int number);

    public Loader(String dir)
    {
        this.dir = dir.replace("\\", "/") + "/";;
    }

    public String formatName(String name) 
    {
        return dir + name + EXTENSION;
    }
}

Its subclasses should be able to change the EXTENSION

public class MidiLoader extends Loader
{
    private String EXTENSION = ".mid";

    public MidiLoader(String dir)
    {
        super(dir);
    }

    public MidiLoader()
    {
        super(Constants.SOUNDDIR);
    }

    @Override
    public Sequence load(String file)
    {
        blah
    }

    public List<Sequence> loadList(String file, int number)
    {
        blah
    }

}

The EXTENSION ".mid" should be used by Loader's formatName function. How do I get it to do this (without duplicating code)?

Thanks.


Solution

  • Have a constructor

    protected Loader(String dir, String ext)
    

    This way the extension is determining by the sub-class.

    BTW making a constructor for an abstract class public could be confusing as it cannot be used publicly.