繁体   English   中英

隐式扩展 Object

[英]Extending Object implicity

Everyone knows that Object is the super class and all the classes which does not extend any other class will extend Object class implicitly. 我想知道这个隐式扩展是如何工作的。

我们有一个文件 child.java

class Child
{
    public static void main(String[] args)
    {
        System.out.println(new Child().toString());
    }
}

As we can see from the above code, in fact, the parent class of the Child class is Object, so we can use the public or protected resources of the Object class, such as the toString method, in Child. 那么Java编译器和JVM是怎么做到的呢?

知道这个原因,其实并不需要知道JVM的实现细节。 想想这个虚拟机程序的原理。 一般来说,对于运行在虚拟机上的这类语言(如Java),有两种方法可以处理默认的inheritance问题。

  1. During compiling the source code stage, if encountering a class without a parent class, the compiler will assign it a default parent class (usually Object), and If the virtual machine processes the class, since the class already has A default parent class, so VM 仍将以通常的方式处理每个 class。 在这种情况下,从编译二进制的角度来看,所有类都将有一个父类 class。

  2. 编译器仍然使用实际代码进行编译,并且不进行额外处理。 如果 class 没有显式继承自其他类,并且编译后的代码仍然没有父 class。 Then when the binary code is run by the virtual machine, if a class without a parent class is encountered, the class is automatically treated as a subclass of the Object class (generally the default parent class is Object).

从以上两种情况可以看出,第一种情况是编译器上的一篇文章,即没有父class时,编译器在编译时自动为其分配一个父class。 第二种情况是在虚拟机上做文章,即虚拟机添加默认父class。

那么Java是哪种情况呢? 事实上,我们可以通过使用 javap 得到这个答案。 随便找个反编译工具,反编译.class文件看看编译器是怎么编译的。 以上面的代码为例。 If it is the first case, even if the Child has no parent class since the compiler has automatically added an Object parent class to Child, the Child class in the source code obtained after decompilation is Inherited from the Object class. 如果不是这种情况,那么是第二种情况。

首先,编译child.java为Child.class

%javac child.java

现在我们用JDK的反编译工具javap来反编译Child.class,首先执行如下命令:

 % javap -c Child

在命令之后,我们的字节码以某种易读的形式出现,我们可以在其中识别我们的方法、整数、命令和字符串

class Child {
  Child();
    Code:
       0: aload_0
       1: invokespecial #1         // Method java/lang/Object."<init>":()V
       4: return

  public static void main(java.lang.String[]);
    Code:
       0: getstatic  #2 // Field java/lang/System.out:Ljava/io/PrintStream;
       3: new     #3 // class Child
       6: dup
       7: invokespecial #4         // Method "<init>":()V
      10: invokevirtual #5         // Method java/lang/Object.toString:()Ljava/lang/String;
      13: invokevirtual #6         // Method java/io/PrintStream.println:(Ljava/lang/String;)V
      16: return
}

As can be seen from the above the piece of code, Test has been inherited from Object, so it can be concluded that Java is the first case of the property, that is, the compiler specifies Object as its default parent class for the class without父 class。

暂无
暂无

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

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