Search code examples
javainheritanceconstructorfactory-pattern

Can you write an interface that requires a no-arg constructor or factory in Java?


In Java, is there a way to enforce a constraint that any Class that implements an interface has a no-arg constructor? If not can you enforce that it has a factory that returns an instance of the class?


Solution

  • Not on the interface, but you can write a class with a factory method:

    public abstract class Foo {
    
        private Foo() {}
    
        public static Bar createBar() {
            return new BarImpl();
        }
    
    }
    
    public interface Bar {}
    
    Bar myBar = Foo.createBar();
    

    That's how Java exposes their factory methods on classes like Calendar.java.