Handling of `final` by the JVM

烂漫一生 提交于 2019-12-06 07:37:23

Yes, you're right.


For classes marked as final, see The Java Virtual Machine Specification: Java SE 8 Edition, §4.10 "Verification of class Files", which says in part:

[…] the Java Virtual Machine needs to verify for itself that the desired constraints are satisfied by the class files it attempts to incorporate. A Java Virtual Machine implementation verifies that each class file satisfies the necessary constraints at linking time (§5.4).

[…]

[…] there are three additional checks outside the Code attribute which must be performed during verification:

  • Ensuring that final classes are not subclassed.
  • […]

(See there for many more details, including what the JVM is supposed to do when a class file violates this constraint.)


For fields marked as final, see ibid., §§6.5–6 "putfield" and "putstatic", which say in part of putfield:

Otherwise, if the field is final, it must be declared in the current class, and the instruction must occur in an instance initialization method (<init>) of the current class. Otherwise, an IllegalAccessError is thrown.

and likewise of putstatic, but with "the <clinit> method" instead of "an instance initialization method (<init>).

(As you may have guessed, putfield and putstatic are the bytecode instructions for setting instance and static fields, respectively.)

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!