Reputation: 23
Could someone explain why any class object may call the toString method even if the class does not provide an implementation for the method.
What happens in this situation and what happens when a class does provide a toString method implementation?
Upvotes: 1
Views: 2334
Reputation: 4134
Every Java class is a subclass of Object class.
Thus, by inheritance, all the operations available in Object class are available in every Java class. This includes toString() operation :).
Upvotes: 4
Reputation: 975
Basically, since every class extends Object
, calling toString calls the Object
implementation, unless the class provides it's own implementation. The default method returns a String containing some information about the class. Overriding it allows you to return anything you want.
See here: https://docs.oracle.com/javase/7/docs/api/java/lang/Object.html#toString()
Upvotes: 1
Reputation: 6104
Every class in java extends from Object class, it's a singly rooted hierarchy, the Object class has a defined toString method so when you try to invoke it with your class object, it works!
Since the toString method gets inherited from the Object class to your class
Morevoer, you can override the toString method in any of your class, it's return type is String, so after overriding the method, if you call toString with your class's object then it will execute the toString method you wrote in that class of yours and not the one Object class supplies by default
Upvotes: 3