简体   繁体   中英

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.

I studied python and I learned how a python class gets constructed,

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.

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.

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. So having 'seen' the name Abc already it can quite readily interpret it at first pass.

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. When it reaches the class variable it can immediately determine the class exists or will exist depending how you look at it.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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