Joel Min
Joel Min

Reputation: 3457

Alternative of static abstract methods in Java

I'm in a situation where I need all my child classes to implement a common abstract method of a parent class...statically. But apparently Java does not allow abstract static methods...

So, what is an alternative design of such implementation in Java? Below is the code that describes the situation I am in:

Parent class

public abstract class ParentFactory {
    /**
    * This is a factory class that provides static init method
    **/
    public abstract static void init();
}

Child class

public class ChildFactory extends ParentFactory {
    @Override
    public static void init() {
        // each child factory has own implementation of init
    }
}

EDIT

FYI, I am not asking why this is not valid in Java, I realise the concept of a static method, I know why it is not allowed in Java.

Instead I am asking for help with an alternative design pattern regarding my approach above. Thanks!

Upvotes: 1

Views: 1987

Answers (4)

Dirk Fauth
Dirk Fauth

Reputation: 4231

I think your problem is in the understanding of the factory pattern. The typical answer to your question would be "use the factory pattern". Because in a factory you could call init on the concrete instance. If you are not using dependency injection and making use of loose coupling through inversion of control, a factory is typically implemented as a singleton. This is to get it from anywhere and there should only be one instance of a factory.

In short, if you want to initialize a factory because you want to subclass the factory (which doesn't make much sense IMHO), you need to create a factory that creates your factory.

Upvotes: 1

You might implement ChildFactory as singleton.

See https://en.wikipedia.org/wiki/Singleton_pattern

Upvotes: 1

greenPadawan
greenPadawan

Reputation: 1571

If you create a static method, then that method can be accessed with the class itself, i.e. without creating an instance of that class. Therefore, a static method can't be abstract.

Upvotes: 2

If a method is static overriding it makes no sense because inheritance does not apply... that is the reason...

Static code is code related to a class and not to an object or an instance.

you need to modify your code...

Upvotes: 1

Related Questions