Reputation: 189
Object class is the base class of every class, i.e, every class extends Object class. There is a public String toString() method in Object class and the same method is present in String class even. Now, the String class also extends Object class and the method toString returns a String type.
My question is-: While compiling the Object class, it will search for the String.class and the String class will search for Object.class creating a type of interdependency. How this dependency is resolved? How the compilation mechanism works? Please correct me if I am wrong somewhere.
Upvotes: 9
Views: 791
Reputation: 3324
The Java compiler is a Multi-Pass Compiler. This means that there are incremental steps in the compile procedure. While compiling Object
, it uses a temporary representation of String
so to allow Object
to compile.
You can compare the temporary representation with some sort of hidden interface. The compiler compiles to that interface. Only at runtime the compiled parts come together - the compiler doesn't need a fully compiled class to compile another class, only an abstraction of it.
Upvotes: 4
Reputation: 1493
Actually, while you write such codes:
public class Class1
{
public Class2 giveClass2()
{
return new Class2();
}
}
public class Class2 : Class1 { }
It compiles correctly because it does not instantiate anything. The compiler just checks if the types you use is defined or not.
However, if you write it as below:
public class Class1
{
public Class1(){
aClass2 = new Class2();
}
public Class2 aClass2;
}
public class Class2 : Class1
{
}
This will also get compiled, but it causes Stack-overflow at run time because then the cyclic dependencies impact.
Upvotes: 2