Jimmy
Jimmy

Reputation: 10341

How to resolve abstract static method design issue?

I have several queues that all extend a Queue class. I want to do a Queue manger base class to handle adding to the queue (and other operations).

If you take a look at the following code, I created a base class called QueueManger that has a static method called add() that will get 'Queue' and add a variable to it. I want to make getQueue() (called in add() ) abstract because I want to force other classes to provide their own implementation of the 'Queue'. The issue is I can't declare abstract static method. What is the right way to solve this?

public class RegistrationQueueManger {
    @Override
    Queue getQueue() {
        return new RegistrationQueue(); // RegistrationQueue is a class that
                                        // extends Queue.java
    }
}

public abstract class QueueManger {
    abstract static Queue getQueue(); // Error: cant do! (in java)

    public static Add(String myvar) {
        getQueue().add(myvar);
    }
}

Note: I saw some question about this subject but it didn't really give a good answer of how to solve it and create another design to handling it.

Upvotes: 0

Views: 2201

Answers (3)

Bhesh Gurung
Bhesh Gurung

Reputation: 51030

That's because abstract method has to be overridden (implemented) and static method is not inherited. Anything that's static belongs to the class itself where it's declared. So, if you if you make getQueue() static it will be a class method that will belong to the class QueueManger class itself. So, make it an instance method, so that every class that extends the QueueManger will have their own getQueue().

Upvotes: 1

JB Nizet
JB Nizet

Reputation: 692071

Only instance methods may be overridden. So abstract on a static method doesn't make sense. The getQueue method shouldn't be static, and the add method shouldn't be static either.

Upvotes: 3

Related Questions