If Object is the mother of all classes in the hierarchy, how can he implement a method returning an object of a child class (e.g toString returns a String object)?
-
4+1 "Object is the mother of all classes" - lolBohemian– Bohemian ♦2011-09-15 12:24:13 +00:00Commented Sep 15, 2011 at 12:24
3 Answers
That's an interesting point: The Object class knows about one of its subclasses, namely String (in particular, to declare and implement the toString() method).
Part of the java language specification is that all classes are implicitly subclasses of Object. Although technically it is "poor design" for a class to refer to one of its subclasses, I think it's an "edge case" and not something to be worried about.
Comments
because there is a default implementation of toString on Object that makes sure a String instance is returned. Since every class is an instance of an Object you always get that default implementation for free, although you can and should implement toString on subclasses.
There is nothing preventing methods in any class returning instances of another class. You can always do
return new SomethingElse()
where SomethingElse is another class.