简体   繁体   English

Java Object超类

[英]Java Object superclass

I have a weird Java question: 我有一个奇怪的Java问题:

As we know: 据我们所知:

  1. All Java classes extend java.lang.Object 所有Java类都扩展了java.lang.Object
  2. All Java classes cannot extend itself 所有Java类都无法扩展自己

Then, java.lang.Object must extend java.lang.Object , which is itself, therefore, it should be impossible. 然后, java.lang.Object必须扩展java.lang.Object ,因为它本身是不可能的。 How is Object implemented in Java? 如何用Java实现Object?

Object is an exception to the first rule, and has no superclass. Object是第一个规则的例外,没有超类。 From JLS3 8.1.4 : 来自JLS3 8.1.4

The extends clause must not appear in the definition of the class Object, because it is the primordial class and has no direct superclass. extends子句不能出现在Object类的定义中,因为它是原始类并且没有直接的超类。

You can also try it out with reflection: 你也可以用反射来试试:

Object.class.getSuperclass(); // returns null

You'd be better off thinking of this as: 你最好把它想象成:

  1. All java classes must implement the interface implied by the methods in java.lang.Object. 所有java类都必须实现java.lang.Object中方法隐含的接口。
  2. The concrete class java.lang.Object provides default implementations of these functions. 具体类java.lang.Object提供了这些函数的默认实现。
  3. All other java classes are derived from the object java.lang.Object and may choose to use or override the default implementations of the methods. 所有其他java类都派生自对象java.lang.Object,并且可以选择使用或覆盖方法的默认实现。

The two main points are: all the classes must implement the implied interface and the Java language spec gives you (forces upon you?) default implementations for these methods for free. 两个要点是:所有类必须实现隐含的接口,Java语言规范为您提供(强制对您?)这些方法的免费默认实现。

Object does not extend itself. 对象不会扩展自己。 It is the superclass for all other objects in the Java language. 它是Java语言中所有其他对象的超类。 Think of it as being the level-0 (or root) class of all the objects in the Java API tree - including any objects you create as well. 可以将其视为Java API树中所有对象的0级(或根)类 - 包括您创建的任何对象。

I also just want to point out that your question is proven impossible by rule #2 that you posted. 我还想指出,您发布的规则#2证明您的问题不可能。 Your logic used to justify your question only takes #1 into account and is therefore extremely flawed. 用于证明你的问题的逻辑只考虑#1,因此存在极大的缺陷。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM