java - 接口(interface)隐式声明 Object 类的公共(public)方法?

标签 java inheritance interface jls

这个问题在这里已经有了答案:





How methods of Object class be visible through interface?

(1 个回答)


2个月前关闭。




根据 The Java Language Specification, Java SE 16 Edition (JLS) §9.2 Interface Members :

If an interface has no direct superinterface types, then the interface implicitly declares a public abstract member method m with signature s, return type r, and throws clause t corresponding to each public instance method m with signature s, return type r, and throws clause t declared in Object (§4.3.2), unless an abstract method with the same signature, same return type, and a compatible throws clause is explicitly declared by the interface.


为什么任何顶级接口(interface)“隐式”声明 的公共(public)方法对象 类(class)?这个设计的目的是什么?

最佳答案

What is the purpose of this design?


因为你希望能够拨打所有 Object 任何类型的每个对象上的方法( toString equals hashCode 等)。
interface Foo {
  
}

Foo foo = ...;

foo.equals(otherFoo);
我是否真的声明了 equals 并不重要接口(interface)中的方法。

关于java - 接口(interface)隐式声明 Object 类的公共(public)方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68874966/

相关文章:

iPhone 开发 - 手动旋转 View

java - 如何阻止 Java 将作为命令行参数传递的 JSON 字符串分离到 args[] 的单独子单元中

java - 数组列表中的最小生成树

java - 有没有比使用反射通过继承层次结构中的工厂方法实例化元素更好的方法?

c++ - 基本深拷贝(操作重载)

Silverlight自定义控件继承。重复使用模板?

go - func() 在自定义结构类型上时的接口(interface)转换

c# - 在设计 C# 类库时,什么时候应该选择继承而不是接口(interface)?

java - 多行 lambda 比较器

java - 匹配和删除 ArrayList 中的项目