Variables in Interface

前端 未结 5 1994
长情又很酷
长情又很酷 2020-12-11 02:05

Why is that a variable used in an Interface is PUBLIC STATIC FINAL? Why \"static\" in particular?

5条回答
  •  心在旅途
    2020-12-11 02:44

    The main reason I guess is implementation detail of the VM/language.

    If an interface is not allowed to have non-static variables, there's no need to allocate memory for the interface during the creation of the class. There's also no need for special naming/renaming mechanisms in case you inherit variables with the same name. The only thing you need is some table to call the correct functions when the interface is used.

    In short - it makes the live of the language / VM maintainer easier. If you really want to take a look at multiple inheritance and its pitfalls and traps, read Object Oriented Software Construction by Bertrand Meyer (2nd Edition). Then you understand why the interface needs to be so simple (and yet archives most of the things multiple inheritance does).

提交回复
热议问题