0

I'm trying to do a factory with devices depending on a fileName with the appropriate device corresponding to it.

My first intuitive approach to avoid creating instance was to define static methods to validate the fileName into its different classes, let's say MyDevice1.validFilePath(fileName) return new MyDevice() but it seems that its not possible to force the implementation of a static method from the Device ancestor.

So I went for polymorphism, and surprise, it seems that compiler complains because he cannot convert MyDevice to Device<Number>. What should I do? Polymorphism applies at compilation because MyDevice is a valid class, but MyDevice cannot be a Device<Number>?

public abstract class device<T extends Number>{
    
    protected List<T> samples;

    public abstract boolean validFileName(String fileName);

}

public class MyDevice extends device<Double>{

    public boolean validFileName(String fileName){
        return fileName.contains("MyDevice");
    }
}

public class DeviceFactory{

    public static Device<Number> getDevice(String fileName){
        Device<Number> res;
        MyDevice md = new MyDevice();
        if (md.validFileName(fileName)){
            res = md;// invalid??!!!
        }else{
            throw new UnsupportedOperationException();
        }
    
        return res;
    }

}

It seems that changing the Device<Number> with Device passes at compilation, but complaining about Device is a raw type. References to generic type Device<T> should be parameterized. Should I just ignore this error in that case? What is the way to go?

khelwood
  • 55,782
  • 14
  • 81
  • 108
Pipo
  • 4,653
  • 38
  • 47
  • 1
    If you return a `MyDevice`, why not make that your return type? `MyDevice` isn't a `Device`, it's a `Device`, which is a `Device extends Number>`. – Andy Turner Apr 19 '21 at 18:44
  • 1
    A `Device` is not a `Device`. It *is* a `Device extends Number>`, so you could use that if you wanted. – khelwood Apr 19 '21 at 18:45
  • @khelwood that is the answer I was looking for `Device extends Number>`!! Thank you very much, that deserves an answer... – Pipo Apr 19 '21 at 19:03

0 Answers0