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.
toString() method returns a string representation of the object. In general, the toString method returns a string that "textually represents" this object. The result should be a concise but informative representation that is easy for a person to read.
What is toString()? A toString() is an in-built method in Java that returns the value given to it in string format. Hence, any object that this method is applied on, will then be returned as a string object.
Every class in Java is a child of the Object class either directly or indirectly. And since the Object class contains a toString() method, we can call toString() on any instance and get its string representation. In this tutorial, we'll look at the default behavior of toString() and learn how to change its behavior.
The toString() method of java. lang. Package class is used to get the String representation of this package instance. The method returns the String representation as a String value.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With