如果我们运行派生类,它将打印派生类和父类。有什么方法可以防止静态 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/