2

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?

Clarke
  • 185
  • 10

1 Answers1

1

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.

Persixty
  • 8,165
  • 2
  • 13
  • 35
  • 1
    So you are saying that at the first pass the compiler can create a symbol of type `class` with the name `ABC`. Then when it reaches to interpret the type of instance variable it sees that symbol. – Clarke Jun 04 '21 at 11:35
  • what do you mean by _depending how you look at it_ – Clarke Jun 04 '21 at 11:35
  • @Clarke I'm talking about a symbol that is show marked as 'incomplete'. It's as simple as whether something is incomplete 'exists' (but is incomplete) or doesn't yet 'exist' (because it's incomplete) but is going to exist. – Persixty Jun 08 '21 at 11:10