Raga Saleh
Raga Saleh

Reputation: 9

java polymorphism creating object

I need to make a program that run process on text, audio and video files,

I create an interface class and three class that inherit it

public interface FileProcess{
    public void process();    
}

public class TextProcess implements FileProcess{ 
    public void process(){System.out.print("Im Text file")};
}

public class VideoProcess implements FileProcess{ 
   public void process(){System.out.print("Im Video file")};
}

public class AudioProcess implements FileProcess{ 
   public void process(){System.out.print("Im Audio file")};
}

I run test that get File from post request (for example a.jpg or 12.txt or aaa.pdf) how can I know what file process to run? in other words how can I know which object process should be created?

Upvotes: 0

Views: 100

Answers (1)

Jordi Castilla
Jordi Castilla

Reputation: 26961

First note your methods are not correct, a " is missing:

public class VideoProcess implements FileProcess{ 
   public void process(){System.out.print("Im Video file")};
   //                                                   ^ here!
}

Either you don't have ImageProcess object...


This is a classic Factory Pattern . To achieve the correct behaviour, in this case, you can create a generic object and check the extension to create concrete instances:

FileProcess process = null;
String filename = "a.jpg";
String extension = filename(0, filename(lastIndexOf(".");

And use it to choose what kind of object create:

switch(extension) {
    // catch multiple image extensions:
    case "jpg":
    case "png":
        process = new VideoProcess();
        break;

    // catch text
    case "txt":
        process = new TextProcess();
        break;

    // catch multiple audio extensions:
    case "wav":
    case "mp3":
        process = new AudioProcess();
        break;

}

Also I would highly reccomend to use a Factory class as described in the link (STEP 3) that returns the correct object.

Upvotes: 5

Related Questions