ceving
ceving

Reputation: 23826

How to substitute an abstract class with an interface in Java?

I have an abstract class Work with two abstract methods (init and work) and one concrete method (run) working with the abstract methods.

class work
{
    abstract static class Work<T> implements Runnable
    {
        T data;

        abstract protected void init ();
        abstract protected void work ();

        public void run ()
        {
            init();
            work();
            System.out.println (data);
        }
    }

    public static void main (String[] args)
    {
        Runnable hello = new Work<String>() {
            protected void init () { data = "Hello $1!"; }
            protected void work () { data = data.replace ("$1", "World"); }
        };

        (new Thread(hello)).start();
    }
}

In order to get rid of the multiple inheritance problem I would like to convert the abstract class into an interface. But in Java interfaces can not contain a body. So where do I have to put the generic data and method after converting the abstract class into an interface?

I fear that it is not possible to get rid of the multiple inheritance problem as long as I want to share anything concrete. Is this right?

Upvotes: 0

Views: 1370

Answers (2)

kuporific
kuporific

Reputation: 10322

You might have to separate the interface from the functionality; something like this:

public interface Work<T> {
    void init();
    T work();
}

public class Worker<T> implements Runnable {

    private final Work<T> work;

    Worker(Work<T> work) {
        this.work = work;
    }

    public void run () {
        work.init();
        T data = work.work();
        System.out.println(data);
    }
}

public static void main (String[] args)
{
    Runnable hello = new Worker<String>(new Work<String>() {
        private String data;
        public void init () { data = "Hello $1!"; }
        public String work () { return data.replace ("$1", "World"); }
    });

    (new Thread(hello)).start();
}

Upvotes: 1

Jean Logeart
Jean Logeart

Reputation: 53829

You can do something like:

  1. Create the Work interface
  2. Create the AbstractWork class which is the abtract class implementing Work and containing the generic code
  3. Create your implementation classes extending AbstractWork

That is exactly what is used in the JDK with List (the interface), AbtractList (the abstract class implementing List) and LinkedList and ArrayList (the implementation classes extending AbstractList).

Upvotes: 2

Related Questions