简体   繁体   English

java 编译器如何允许 class 拥有自己的类型引用?

[英]How does java compiler allow a class to have its own type reference?

I am wondering about this below code,我想知道下面的代码,

public class Abc {
    private Abc p;
}

When the class is compiled how does the compiler know of the type ABC , since the type ABC hasn't came to existence yet.编译 class 时,编译器如何知道类型ABC ,因为类型ABC还没有出现。

I studied python and I learned how a python class gets constructed,我研究了 python 并了解了如何构建 python class,

class Person:
  def __init__(self, name, age):
    self.name = name
    self.age = age

In the above python code, the name Person gets assigned to the corresponding class object, after all variable and method definitions inside that class.在上面的 python 代码中,名称Person被分配给对应的 class object,在 ZA2F2ED4F8EBC2CBBD4C21 中的所有变量和方法定义之后。

I would like to know about how a java class gets constructed under the hood and how it can contain a reference type of its own type.我想知道如何在引擎盖下构建 java class 以及它如何包含自己类型的引用类型。

Can someone provide me a deep explanation on that or give me a good reference book for those topics regrading to what happens under the hood?有人可以为我提供一个深入的解释,或者给我一本很好的参考书,让我了解那些从幕后发生的事情吗?

Remember in Java a class variable is just a reference variable.请记住,在 Java 中,class 变量只是一个参考变量。 So having 'seen' the name Abc already it can quite readily interpret it at first pass.所以已经“看到”了Abc这个名字,它可以很容易地在第一次通过时解释它。

There's no obligation for it to do so but you can imagine a compiler that records a symbol of type class with name Abc and an internal state of 'incomplete' when first declared.它没有义务这样做,但您可以想象一个编译器记录一个类型为class的符号,名称为Abc ,并且在首次声明时内部 state 为“不完整”。 When it reaches the class variable it can immediately determine the class exists or will exist depending how you look at it.当它到达 class 变量时,它可以立即确定 class 存在或将存在,具体取决于您如何看待它。

That doesn't make single pass compiling possible but that's because of things like you can declare methods in any order including methods that call each other which can't be compiled 'single pass'.这不会使单遍编译成为可能,但这是因为您可以按任何顺序声明方法,包括无法“单遍”编译的相互调用的方法。 There are other cases where you can make 'forward' references in Java classes that mean they're not always single-pass compilable.在其他情况下,您可以在 Java 类中进行“前向”引用,这意味着它们并不总是可以单遍编译。

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

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