Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How Object objects return Strings? (Java)

Tags:

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

like image 806
Ken Avatar asked Sep 15 '11 12:09

Ken


People also ask

How do you return a string from an object in Java?

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.

Can object be converted to string in Java?

We can convert Object to String in java using toString() method of Object class or String. valueOf(object) method. You can convert any object to String in java whether it is user-defined class, StringBuilder, StringBuffer or anything else.

Which method converts objects to string?

toString() The toString() method returns a string representing the object.

How do we get a string representation of an object?

The toString() method returns the string representation of an object. A default implementation of this method is included in the Object class. This implementation returns a string containing the name of the object's class and its hash code.


1 Answers

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 {

}
like image 104
MByD Avatar answered Oct 17 '22 07:10

MByD