When is an interface with a default method initialized?

前端 未结 4 1773
失恋的感觉
失恋的感觉 2020-11-30 18:18

While searching through the Java Language Specification to answer this question, I learned that

Before a class is initialized, its direct superclass m

4条回答
  •  隐瞒了意图╮
    2020-11-30 18:54

    I'll try to make a case that an interface initialization should not cause any side-channel side effects that the subtypes depend on, therefore, whether this is a bug or not, or whichever way the Java fixes it, it should not matter to the application in which order interfaces are initialized.

    In the case of a class, it is well accepted that it can cause side effects that subclasses depend on. For example

    class Foo{
        static{
            Bank.deposit($1000);
    ...
    

    Any subclass of Foo would expect that they'll see $1000 in the bank, anywhere in the subclass code. Therefore the superclass is initialized prior to the subclass.

    Shouldn't we do the same thing for superintefaces as well? Unfortunately, the order of superinterfaces are not supposed to be significant, therefore there is no well defined order in which to initialize them.

    So we better not establish this kind of side effects in interface initializations. After all, interface is not meant for these features (static fields/methods) we pile on for convenience.

    Therefore if we follow that principle, it'll be no concern to us in which order interfaces are initialized.

提交回复
热议问题