gpt4 book ai didi

java - 使用公共(public)字段以外的 getter/setter 来实现二进制兼容性?

转载 作者:搜寻专家 更新时间:2023-10-31 20:22:31 25 4
gpt4 key购买 nike

我正在阅读“实用 API 设计”并找到以下段落:

在 JVM 规范中可以找到优先使用方法而不是字段的另一个原因。您可以将方法从一个类移动到它的父类(super class)之一,并且仍然保持二进制兼容性。因此,一个方法最初作为 Dimension javax.swing.JComponent 引入。getPreferredSize(Dimension d) 可以在新版本中删除并移至 Dimension java.awt.Component.getPreferredSize(Dimension d),因为 JComponent 是 Component 的子类。A在JDK 1.2中确实发生了这样的变化,只是因为字段被方法封装了才可以做到。字段不允许这样的操作。字段一旦定义在类中,它就必须永远留在那里保持二进制兼容性,这是保持字段私有(private)的另一个原因

因为我同意使用 getter/setter 是更好的方法。但我不明白为什么将公共(public)字段移至父类会破坏二进制兼容性?只要它在父类中是公共(public)的,您仍然应该能够通过子类访问该字段。

最佳答案

Once a field is defined in a class, it has to stay there forever to maintain binary compatibility

那将是非常令人惊讶的:

Java 语言规范,Java SE 7 版,defines非限定字段访问表达式的二进制名称如下:

Given a legal expression denoting a field access in a class C, referencing a non-constant (§13.4.9) field named f declared in a (possibly distinct) class or interface D, we define the qualifying type of the field reference as follows:

  • If the expression is of the form Primary.f then:
    • If the compile-time type of Primary is an intersection type (§4.9) V1 & ... & Vn, then the qualifying type of the reference is V1.
    • Otherwise, the compile-time type of Primary is the qualifying type of the reference.

(Java 1.5 语言规范 uses 完全相同的措辞)

也就是说,字段访问表达式的二进制名称不引用声明该字段的类型,仅引用我们用来访问该字段的主要表达式的类型,因此无论该类型的哪个父类(super class)声明该字段,编译器需要相同字段引用发送到类文件中。

的确,刚才我尝试进化的时候

package p;

public class Super {

}

package p;

public class Sub extends Super {
public String message;

@Override
public String toString() {
return message;
}
}

package p;

public class Super {
public String message;
}

package p;

public class Sub extends Super {
@Override
public String toString() {
return message;
}
}

无需重新编译

package p;

public class Main {
public static void main(String[] args) {
Sub sub = new Sub();
sub.message = "hello";
System.out.println(sub);
System.out.println(sub.message);
}
}

我仍然收到

的输出
hello
hello

,不是 LinkageError

总而言之,这种说法对于 Java 7 是不正确的。对于 JDK 1.4 或更早版本,它可能是正确的,它在 5 年多前就被宣布停产。无论哪种方式,也许您应该使用一本更好/更新的书?

关于java - 使用公共(public)字段以外的 getter/setter 来实现二进制兼容性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10017995/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com