- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
我正在阅读“实用 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/
我已经坚持了好几天了……很抱歉遇到这样的问题,但是我只是F#本身的初学者。由于关于类型提供程序的讨论很多,所以我决定建立一个类型提供程序并撰写一篇有关它的论文。当我开始时,我不知道什么是类型提供程序。
我正在开发LAN项目唤醒功能,但是我想控制局域网中计算机是否打开。但是我不想使用ICMP或WMI(我的网络上有DC)。那么,对于此问题,是否还有其他选择,例如“套接字连接”,请检查特定端口是否正在使用
我们有一个旧的VB6应用程序,该应用程序使用Crystal Reports XI生成打印报告。我们已经通过经验发现,如果Crystal Reports打印引擎选择了错误版本的 usp10.dll (W
我正在尝试获取有效的 Android 权限列表。我知道 http://developer.android.com/reference/android/Manifest.permission.html
嗨,我是 nginx 的新手,我试图在我的服务器(运行 Ubuntu 4)上设置它,它已经运行了 apache。 所以在我 apt-get install 它之后,我尝试启动 nginx。然后我收到这
如何在VB 6中检查对象的类型-除了'TypeName'之外,是否还有其他方法,因为无法通过'TypeName'进行检查,我希望使用类似QuichWatch窗口的方法。 最佳答案 对于对象变量,请使用
我的 JSP 应用程序中有一个错误。发布后我的 session 被清除: YAHOO.util.Connect.asyncRequest('POST', Url, callback, post
我是一名优秀的程序员,十分优秀!