3

Of course, the following doesn't work in Java (no abstract static methods)...

public abstract class Animal {
    public abstract static Animal getInstance(byte[] b);
}

public class Dog extends Animal {
    @Override
    public static Dog getInstance(byte[] b) {
        // Woof.
        return new Dog(...);
    }
}

public class Cat extends Animal {
    @Override
    public static Cat getInstance(byte[] b) {
        // Meow.
        return new Cat(...);
    }
}

What's the correct way of requiring that Animal classes have a static getInstance method that instantiates itself? This method should be static; a "normal" abstract method doesn't make sense here.

  • Related: http://stackoverflow.com/questions/129267/why-no-static-methods-in-interfaces-but-static-fields-and-inner-classes-ok and http://stackoverflow.com/questions/708336/beginner-factory-pattern-in-java – finnw Jul 17 '10 at 00:18

1 Answers1

6

There is no way to specify in an abstract class (or interface) that an implementing class must have a particular static method.

It is possible to get a similar effect using reflection.

One alternative is to define an AnimalFactory interface separate from the Animal class:

public interface AnimalFactory {
    Animal getInstance(byte[] b);
}

public class DogFactory implements AnimalFactory {
    public Dog getInstance(byte[] b) {
        return new Dog(...);
    }
}

public interface Animal {
    // ...
}

class Dog implements Animal {
    // ...
}
finnw
  • 47,861
  • 24
  • 143
  • 221
  • 1
    It just doesn't make ANY sense to ask for a new instance from an existing instance, because you can't get one if there are zero instances yet. This is where the classic static factory method comes in (hard to achieve nice design I understand that, because you can't provide static interface or abstract methods). – gyorgyabraham Sep 12 '12 at 14:03