Question

Consider the following sample situation:

public abstract class Parent
{
    private ByteBuffer buffer;

    /* Some default method implementations, interacting with buffer */

    public static Parent allocate(int len)
    {
        // I want to provide a default implementation of this -- something like:
        Parent p = new Parent();
        p.buffer = ByteBuffer.allocate(len);
        return p;
    }
}

public class Child extends Parent
{
    /* ... */
}

public class App
{
    public static void main(String[] args)
    {
        // I want to ultimately do something like:
        Child c = Child.allocate(10);
        // Which would create a new child with its buffer initialized.
    }
}

Obviously, I can't do this (new Parent()) since Parent is abstract, but I don't really want a Parent. I want this method to be automatically provided to subclasses.

I would prefer to use the "static constructor" approach with .allocate() instead of adding another visible constructor.

Do I have any way to put this default implementation in the Parent class, or must each of the subclasses contain the same code?

I guess another option would be to strip "abstract" from the parent, but abstract fits -- I never want an object of type Parent.

Thanks in advance.

Was it helpful?

Solution

If you examine the collection of Buffer classes in the standard JDK you will notice that each specialization (ByteBuffer, CharBuffer, DoubleBuffer etc) each have their own static allocate method defined. There is a reason they do not all inherit from a common base class - static methods are not inherited! Instead they are associated with the class in which they are defined and only have access to class level variables.

A better pattern for what you are trying to accomplish is the builder/factory pattern. You can examine the JAX-RS Response class, or DocumentBuilderFactory classes for examples on how to implement these patterns.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top