Ken
Ken

Reputation: 169

How Object objects return Strings? (Java)

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)?

Upvotes: 13

Views: 2343

Answers (3)

Bohemian
Bohemian

Reputation: 425023

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.

Upvotes: 2

MByD
MByD

Reputation: 137322

This is not a problem as long as the child class exists. For example, the following is valid:

A.java:

public class A {
    B b;
}

B.java:

public class B extends A {

}

Upvotes: 3

hvgotcodes
hvgotcodes

Reputation: 120188

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.

Upvotes: 0

Related Questions