prevent inheritance of static block

前端 未结 2 1859
粉色の甜心
粉色の甜心 2021-01-15 07:36

If we run derived class,it will print derived and parent..is there any way to prevent inheritance of static block ?

//Class 1

public class parent {
s         


        
2条回答
  •  粉色の甜心
    2021-01-15 08:24

    NO. You cannot do that . Static initialzier blocks are not inherited . Static blocks are executed when class is loaded since your base class extends a super class , even the super class definition will be loaded by JVM when referring to your class.

    As per the JLS 12.4.1:

    When Initialization Occurs A class or interface type T will be initialized immediately before the first occurrence of any one of the following:

    • T is a class and an instance of T is created.

    • T is a class and a static method declared by T is invoked.

    • A static field declared by T is assigned.

    • A static field declared by T is used and the field is not a constant variable (§4.12.4).

    • T is a top level class (§7.6), and an assert statement (§14.10) lexically nested within T (§8.1.3) is executed.

提交回复
热议问题