java - 防止静态 block 的继承

标签 java inheritance java-6

如果我们运行派生类,它将打印派生类和父类。有什么方法可以防止静态 block 的继承吗?

//第1类

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

//类2

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

      public static void main(String [] args) {

      }
}

基本上,我在父类中有一些方法,我想继承这些方法,但不希望在实例化派生类时发生在父静态 block 中发生的处理。 .有什么办法可以做到这一点,否则我将不得不重复代码?

最佳答案

不。你不能那样做。 静态initialzier block 不是继承的。静态 block 在类加载时执行,因为您的基类扩展了父类(super class),甚至在引用您的类时,JVM也会加载父类(super class)定义。

根据 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.

关于java - 防止静态 block 的继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17185597/

相关文章:

Java 日历,行为不同 OSX Windows

java - 此时如何解决意外的JDK问题

java - Twitter API - 使用 t.co 缩短推文文本

java - 是否有 python random._urandom() 的 java 等价物?

java - 使用和不使用泛型创建 set/list/map 的实例有多少种合法方法

c++ - 为代码重用而不必要地使用虚函数

Java Object类和多重继承

java - 在不同类的 JTextArea (java) 中加载文本文件

java - 不使用 CSS 更改小部件外观

java - 赋值时,Java三元行为异常。为此,Java在后台做了什么?