Search code examples
javaabstraction

Implement/extends class without implementing all methods


I'm looking to have a method return a class Job, that has different methods based on the job type.
For example, the job type could be BackupJob or RunCommandJob. They don't share methods, but it's needed to get them from a single method, getJob().

Right now I have a normal class job that has the methods return null, without a constructor, since I construct the other classes (BackupJob or RunCommandJob for example) in the getJob() method.

What is the best way to get the different job classes while returning a single class?
example code below.
Job class:

public ArrayList<String> getCommands() { return null; }

public String getBackupGUID() { return null; }

public void setCommands(String... commands) { return; }

public void setBackupGUID(String backupGUID) { return; }
//Etc...

getJob method

public Job getJob() { 
if (JobType == RunCommandsJob) return new RunCommandsJob(...);
else if (JobType == BackupJob) return new BackupJob(...);
//and so on for all the other types

Example of the RunCommandsJob class, but it's the same concept with all the different types, but with unique method names.

public ArrayList<String> getCommands() { /* method */ }
public void setCommands(String... commands) {/* method */ }

Edit: A little bit more context.
I have a scheduler class, that can contain multiple Tasks. Each Task has it's own Job, that could be different things (for example, a RunCommandsJob). Job itself isn't used, but In the other classes I extend Job so that I can return a "Job" that is in reality a "RunCommandsJob", which has logic to edit it in the database/API.
It's complicated, but that's what I have to work with.


Solution

  • You can define Job as an interface or abstract class. So you don't have to write default implementations and concrete classes must implement the methods.