开发者

how to make constructor definition mandatory

开发者 https://www.devze.com 2023-04-12 20:43 出处:网络
I have an interface I that is implemented by a base class B. The base class is extended by a bunch of classes (A,C,D) that must init some of the protected vars declared in base class B. I\'d like to m

I have an interface I that is implemented by a base class B. The base class is extended by a bunch of classes (A,C,D) that must init some of the protected vars declared in base class B. I'd like to make the declaration of a constructor mandatory in the subclasses (A,C,D), to discourage the user from relying on default constructor that's declared in B. Yet I do want the B's default constructor to execute automatically, since B can be used by itself as well. How can I accompl开发者_如何学运维ish this?

thanks


Use an abstract superclass of B with a private constructor:

public abstract class BSuper {

    private BSuper() {
        // initialize stuff
    }

    protected BSuper(some params) {
        this():
        // other init with parms
    }
}


public class B extends BSuper {

     public B(some other params) {
         super(some params);
     }
}


public class A extends B {

     public A() {
         super(some other params);
     }
}

or similar


Make B's default constructor private and call this(); from within the parameterized constructor...

public class B {
    private B() {
        super();
    }
    public B( Foo foo ) {
        this();
    }
    public static B createInstance() {
        return new B();
    }
}

Edit: Miss read the issue, removed abstract keyword from class declaration. Also added public static factory method for creating B class. It calls B's default constructor.


Just write a comment in the Javadoc that says "Use of default constructor is discouraged when subclassing." In my experience, trying to enforce that programmatically is not worth the effort and could cause problems latter on. Simple English will do.


If class B is going to have its own default constructor, what you want is impossible. When you derive from a class, you're telling the compiler that it should allocate memory for a base class object in every instance of the derived class. There's no way to tell a java compiler to suddenly take away some of the base class's functionality every time that something is inherited from it.

Also note that constructors and static factory methods can't be abstract, so even if B could be an abstract class you would have to do something like:

public class B {

     B() {
          initialize();
     }
     protected abstract void initialize();
}

...along with making sure that the derived classes implement default constructors that call super()

0

精彩评论

暂无评论...
验证码 换一张
取 消