Search code examples
oopinheritancelanguage-agnosticprogramming-languages

How would you implement a toString method, on the base class, if the string class inherits from the base class?


In many modern OOP languages, such as Java and C#, reference types have a base class typically called Object from which all other reference types inherit their core functionality.

These languages also have a universal .toString() method shared across all the reference types, so that it's easy to extract data as a string from it.

Now here's the question: If the String class is a subclass of Object, how can Object implement a .toString() method without causing a circular dependency?

if A uses B and B implements A it's bound to cause problems, or am I totally wrong in this?


Solution

  • Regarding C# (and I'm pretty sure the same goes for Java), the compiler doesn't require that source files be provided in dependency order.

    This means that, unlike other compilers (the F# compiler and gcc, I believe), the C# compiler allows you to refer to symbols that haven't been seen by the compiler yet (as long as both types are in the same assembly).

    In other words - yes, there's is a circular dependency, but the compiler takes care of that for you. If you want to know how compilers handle circular dependencies, then that has been asked on programmers.stackexchange already.