views:

192

answers:

3

I want to create an abstract class in java that forces all its subclasses to implement a SwingWorker (plus the SwingWorker's abstract doInBackground() and done()).

In AbstractClass -

abstract class Task extends SwingWorker<Void, Void>{};

I would expect this to cause the compiler to throw an exception when an extended class doesn't implement it, but it doesn't.

I am also not quite sure how I would go about indicating that I'm overriding this abstract class. Do I redeclare it in the ConcreteClass as follows?

class Task extends SwingWorker<Void, Void>{
  ...
}

or some other way?

Thanks for all your help!

A: 

The first piece of code will compile, because class Task is also marked as abstract and compiler accepts that it doesn't implement abstract members of ancestor. But you will not be able to instantiate it (call new Task(); ). The second piece should not compile, because you didn't implement abstract methods. To see examples scroll down this page: SwingWorker

Andrey
+3  A: 

doInBackground() is abstract in SwingWorker, so any concrete subclass of Task should have to provide an implementation.

done(), however, is not abstract in SwingWorker, so no new implementation is needed. If you want to force your subclasses to reimplement it you need to:

abstract class Task extends SwingWorker<Void, Void>{
    @Override
    protected abstract void done();
}

To create the concrete subclass, just extend Task like you would extend any other class, and override the abstract methods with implementations:

class SubTask extends Task {
    @Override
    protected void done(){
        //implementation
    }

    @Override
    public Void doInBackground(){
        //implementation
    }
}
ILMTitan
+3  A: 

Hi, you need to declare the methods also as abstract, like this:


abstract class Task extends SwingWorker {
    @Override
    protected abstract Void doInBackground();
    @Override
    protected abstract void done();
};
elou
and then how do I override this in the concrete class?
chama
by the way.. class MyImplementationOfTask extends Task { @Override public void doInBackground() { } @Override public void done() { } }
elou