防止继承静态块 [英] prevent inheritance of static block

查看:79
本文介绍了防止继承静态块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我们运行派生类,它会打印派生和parent..is有什么方法可以阻止静态块的继承吗?

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

// Class 1

//Class 1

public class parent {
static {
      System.out.println("Parent");
}
}

// Class2

//Class2

public class derived extends parent{
      static {
            System.out.println("derived");
      }

      public static void main(String [] args) {

      }
}

基本上我在父类中有一些方法我想继承但不希望在实例化派生类时发生在父静态块中发生的处理。 。有什么方法可以做到这一点,或者我必须复制代码吗?

Basically I have some method in parent class which I want to inherit but dont want the processing which is happening in parent static block to happen when derived class is being instantiated. .Is there any way to do this or I will have to duplicate the code ?

推荐答案

NO。你做不到。 静态初始化块不是继承的。静态块是在加载类时执行的,因为基类扩展了超类,甚至超级类定义也会在引用您的类时由JVM加载。

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.

根据 JLS 12.4.1


初始化发生时类或接口类型T将是在第一次出现以下任何一项之前立即初始化:

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

•T是一个类,并且创建了一个T实例。

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

•T是一个类,调用T声明的静态方法。

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

•指定由T声明的静态字段。

• A static field declared by T is assigned.

•使用T声明的静态字段,该字段不是常量变量(§4.12.4)。

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

•T是顶级类(第7.6节)和断言语句(第14.10节)在词典中嵌套在T(§8.1.3)中执行。

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

这篇关于防止继承静态块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆