How an object will call toString method implicitly? - java

If I am printing an object of the class then it is printing the toString() method implementation even I am not writing the toString() method so what are the implementation,how it is calling toString() internally?

You're not explicitly calling toString(), but implicitly you are:
See:
System.out.println(foo); // foo is a non primitive variable
System is a class, with a static field out, of type PrintStream. So you're calling the println(Object) method of a PrintStream.
It is implemented like this:
public void println(Object x) {
String s = String.valueOf(x);
synchronized (this) {
print(s);
newLine();
}
}
As we see, it's calling the String.valueOf(Object) method.
This is implemented as follows:
public static String valueOf(Object obj) {
return (obj == null) ? "null" : obj.toString();
}
And here you see, that toString() is called.

Every object in Java IS-A(n) Object as well. Hence, if a toString() implementation has not been provided by a class the default Object.toString() gets invoked automatically.
Object.toString()'s default implementation simply prints the object's class name followed by the object's hash code which isn't very helpful. So, one should usually override toString() to provide a more meaningful String representation of an object's runtime state.
even I am not writing the toString() method so what are the implementation,how it is calling toString() internally?
toString() is one of the few methods (like equals(), hashCode() etc.) that gets called implicitly under certain programmatic situations like (just naming a few)
printing an object using println()
printing a Collection of objects (toString() is invoked on all the elements)
concatenation with a String (like strObj = "My obj as string is " + myObj;)

Everything inherits from Object, so the toString on Object will be called if you have not defined one.

toString() method is present in Object class, so when u put obj in System.out.println(obj);, impliciyly it will call toString() present in Object class since every user created class will implicitly inherits Object class so as ur newly created class, that means that toString() is available in ur class so it will print something like for example: "PkgNamePackage.Classname#12cf4"
However if u explicitely override toString method and give ur own implementation then it will written the string what ever u give in Overriden tostring method();
ex:
public class DogArray {
#Override
public String toString() {
return "Im the newly created Object";
}
public static void main(String args[]) {
DogArray d1 = new DogArray();
System.out.println(d1);
}
}
output: Im the newly created Object

In java object class is super class to the each and every class.whenever your passing parameter to the system.out.println internally object class to string method will be excuted.it returns class name#reference value given but as per our application requirement object class to string method will override in collection and string class.it returns their content.

Related

Using getClass().getName() in toString() methods

I have the following classes defined:
class BaseClass {
public String toString()
{
return "I am a: " + getClass().getName();
}
}
class DerivedClass {
public String toString()
{
return super.toString();
}
}
In my main() function I have the following code:
BaseClass b = new BaseClass();
DerivedClass d = new DerivedClass();
System.out.println(b);
System.out.println(d); // not sure why/how this works!
As expected, I do get the correct run-time class types when this code runs:
I am a: BaseClass
I am a: DerivedClass
My question is, how exactly does the call to toString() in my DerivedClass work? In my DerivedClass override of toString(), I'm making a call to super.toString() which seems like it should actually return "I am a: BaseClass" because we're calling toString() on the parent class.
I suspect it may have something to do with the fact that my base class toString() utilizes getClass().getName(), so that when I call it through a subclass object, Java must be detecting my actual object type - but I don't know how it knows to do that...
Sorry if this sounds like a noob question, but I'm still wrapping my head around the concept of polymorphism. If anyone could explain why this works the way it does, I'd appreciate any insight.
getClass() is a polymorphic method. It returns the actual concrete class of the object on which it is called. Since d id of type DerivedClass, its getClass() method returns DerivedClass.class.
You would get the result you expect if the method implementation was
return "I am a: " + BaseClass.class.getName();
Imagine your classes looked like this:
class BaseClass {
#Override
public String toString() {
return "I am a: " + getClass().getName();
}
public Class<?> getClass() {
return BaseClass.class;
}
}
class DerivedClass extends BaseClass {
#Override
public Class<?> getClass() {
return DerivedClass.class;
}
}
Because of the way overriding works, getClass() will always return DerivedClass.class when invoked on an instance of DerivedClass, even when called from the superclass BaseClass. Calling super.toString() doesn't change that, and is in fact entirely unnecessary, since the superclass implementation is inherited by default.
Note that this is just a demonstration of what you can expect when calling getClass(). In real life, getClass() is actually a final native method. Overriding it is not possible or necessary.
Your first question is:
System.out.println(d); // not sure why/how this works!
And it is a good question! After all, you are passing the println method a reference, d, to an instance of DerivedClass. Why would that result in actually calling a method that is named toString()?
The answer to this question lies in the Javadoc for the appropriate println method. The compiler (javac) correctly compiles your code to say that you are interested in calling the println method that takes in an Object. Note that println is an overloaded method and compiler must resolve the right method based on passed argument(s). In this case, the method resolves to println(Object x) which states:
Prints an Object and then terminate the line. This method calls at first String.valueOf(x) to get the printed object's string value, then behaves as though it invokes print(String) and then println().
Then you visit the String.valueOf() method and see:
public static String valueOf(Object obj) {
return (obj == null) ? "null" : obj.toString();
}
Bingo! That closes the first loop, either the BaseClass's toString() is called, or DerivedClass's.
The actual reason why the d's getClass() is called has to do with the value of the this reference. As you perhaps know, every instance method in Java (like the toString() one) receives an invisible parameter called the this reference in addition to the arguments that are declared. In this particular case, since the this reference points to d, all the methods are invoked on that reference. The class of d is clearly DerivedClass.

Difference between wrapper class reference and user defines class reference in java

Suppose I have a custom class, say Test.
Test test = new Test(); // test is the reference.
Now when I print the value of test, it returns the hashcode .
Now consider,
Integer i = new Integer(10);
When I print the value of i, it returns 10.
Can someone help me to understand what exactly is the difference here? I believe both are object references, but for wrapper class reference, it returns the value of the object it is pointing to.
When you create a new class, it inherits the method toString() from Object. Integer class overrides that method to return the inner value.
When printing, there is an implicit call to toString() method.
By default (in for your Test class) it uses the one inside Object class. For Integer, it convert the Integer to a String in 10-base.
Your Test class is using Object class's toString() method which prints hashCode. But for Integer class, toString method is overrided. You can see Integer.java here
user defined reference is an object,if you print that object means you may get some hash code because every class extends Object class,so your also have the property (method) tostring().
Wrapper class wraps its respective primitive data type
Integer i = new Integer(10);
and
i=10;
both same in value.
When you call System.out.println(Object) (or, more generally, PrintStream.println(Object)):
This method calls at first String.valueOf(x)
String.valueOf(Object) returns:
if the argument is null, then a string equal to "null"; otherwise, the value of obj.toString() is returned.
Neither of your objects are null, so the toString() method of the instances is called.
In the case of Integer:
The value is converted to signed decimal representation and returned as a string
In the case of Test, unless you've explicitly overridden it (or a superclass has overridden it), you will call Object.toString():
[T]his method returns a string equal to the value of:
getClass().getName() + '#' + Integer.toHexString(hashCode())
If this isn't the desired behaviour, override toString() in Test:
class Test {
#Override public String toString() {
// ... Your implementation.
}
}
Whenever you print the object Java will invoke the toString() method. The default implementation of toString() available in Object Class. Object is the base class for the all the Object in java.
public String toString() {
return getClass().getName() + "#" + Integer.toHexString(hashCode());
}
It will print the class Name with full package path # and HashCode of the object.
The test class doesn't override the toString() method. But all the wrapper class in java override the toString().so when You invoke the Integer method it invoke the toString() implemented in Integer class.

Why calling Java Object Instance executes method of object [duplicate]

This question already has answers here:
when to use toString() method
(9 answers)
Closed 6 years ago.
I've been learning Java currently and am confused about a certain piece of code. I come from a C, Python background, so I'm more learning the syntax and small niches of Java.
Below I have 2 classes. My Main class and a class that contains a method to return the decorated input string of the class.
I'm confused as to why calling myObject automatically calls the "toString()" method which returns the message? Shouldn't I need to define the method I want to call on the object? Why can you do this in Java?
I thought it was because the class is called "OtherClass" and the method inside OtherClass is called "OtherClass" but when I test this hypothesis out with another class, calling the object returns the object and it's address location.
Any help would be great. Thanks!
public class HelloWorld
{
public static void main(String[] args)
{
int i = 0;
OtherClass myObject = new OtherClass("Hello World!");
// This calls method toString()
System.out.print(myObject);
// This calls method toString()
System.out.print(myObject.toString());
}
}
public class OtherClass
{
private String message;
private boolean answer = false;
public OtherClass(String input)
{
message = "Why, " + input + " Isn't this something?\n";
}
public String toString()
{
return message;
}
}
public void print(Object obj)
Prints an object. The string produced by the String.valueOf(Object) method is translated into bytes according to the platform's default character encoding, and these bytes are written in exactly the manner of the write(int) method.
public static String valueOf(Object obj)
Returns the string representation of the Object argument.
public static String valueOf(Object obj) {
return (obj == null) ? "null" : obj.toString();
}
And as #Andreas said in the comments, toString() prints the hashcode if this method isn't overridden by the subclass:
public String toString() {
return getClass().getName() + "#" + Integer.toHexString(hashCode());
}
"I thought it was because the class is called "OtherClass" and the method inside OtherClass is called "OtherClass" but when I test this hypothesis out with another class, calling the object returns the object and it's address location."
In fact, the method which holds the same name as the class(OtherClass for example) is the constructor method, which will be called automatically when you initialize the class.
In this case, when you run OtherClass myObject = new OtherClass("Hello World!");, the constructor method
public OtherClass(String input)
{
message = "Why, " + input + " Isn't this something?\n";
}
is called and set message value.
And when it comes to System.out.print(myObject);, myObject.toString()will be called and return String message.
So the key point here is to override toString() method in your class, you may print whatever message you want by modifying toString()method, if this method is not override, it will return something associate with hashcode. (Just try and enjoy~)
in Java there is a class that called Object, any other classes that you define
inherit from that , it has a method named 'toString'
/**
* Returns a string representation of the object. In general, the
* {#code 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.
* It is recommended that all subclasses override this method.
*
* The {#code toString} method for class {#code Object}
* returns a string consisting of the name of the class of which the
* object is an instance, the at-sign character `{#code #}', and
* the unsigned hexadecimal representation of the hash code of the
* object. In other words, this method returns a string equal to the
* value of:
*
*
* getClass().getName() + '#' + Integer.toHexString(hashCode())
*
*
* #return a string representation of the object.
*/
So you can simply run your main method in debug mode and set a break point
in toString of Object
System.out.println(new Object());
If you want to represent any object as a string, toString() method comes into existence.
If you print any object, java compiler internally invokes the toString() method on the object. So overriding the toString() method, returns the desired output, it can be the state of an object etc. depends on your implementation.
Java was designed to easily print objects as strings.
System.out is a PrintStream (see https://docs.oracle.com/javase/8/docs/api/java/io/PrintStream.html#print-java.lang.Object-)
When you pass an object to the method print (or println), you're actually calling
String.valueOf(Object) (see https://docs.oracle.com/javase/8/docs/api/java/lang/String.html#valueOf-java.lang.Object-)
Which in turn will do the following
"if the argument is null, then a string equal to "null"; otherwise,
the value of obj.toString() is returned."
If your object has an explicit toString() implementation, this method will be called, otherwise the interpreter will try to find an object in the hierarchy that implements it.
This is a build in feature in java. You dont need to write .toString() to print information about the Object.
You can use this feature everywhere, even with java operators:
System.out.print(myObject1 + myObject2);
is the same like:
System.out.print(myObject1.toString() + myObject2.toString());
toString() is a method in java.lang.Object, so every object contains this method. The default implementation displays the hashcode. You can override it with your own implementation.

The connection between 'System.out.println()' and 'toString()' in Java

What is the connection between System.out.println() and toString() in Java? e.g:
public class A {
String x = "abc";
public String toString() {
return x;
}
}
public class ADemo {
public static void main(String[] args) {
A obj = new A();
System.out.println(obj);
}
}
If main class runs, it gives an output as "abc". When I remove the code which overrides toString(), it gives an output as "A#659e0bfd". So, can anyone explain what is the working principle of System.out.println() when I pass the obj object reference as an argument to it? Is it fully connected with toString() method?
System.out is a PrintStream. Printstream defines several versions of the println() function to handle numbers, strings, and so on. When you call PrintStream.println() with an arbitrary object as a parameter, you get the version of the function that acts on an Object. This version of the function
...calls at first String.valueOf(x) to get the printed object's string value...
Looking at String.valueOf(Object), we see that it returns
if the argument is null, then a string equal to "null"; otherwise, the value of obj.toString() is returned.
So, long story short, System.out.println(someObject) calls that object's toString() function to convert the object to a string representation.
If your object defines its own toString() function, then that is what will be called. If you don't provide such a function, then your object will inherit toString() from one of its parent classes. In the worst case, it will inherit Object.toString(). That version of toString() is defined to return
a string consisting of the name of the class of which the object is an instance, the at-sign character `#', and the unsigned hexadecimal representation of the hash code of the object.
Or, in other words:
getClass().getName() + '#' + Integer.toHexString(hashCode())
So, when you call System.out.println() on an object that doesn't define its own version of toString(), you might get the Object version which looks like "classname#someHexNumber".
toString() is a method that exist in the Object class (Root of the inheritence tree) for all classes.
System.out.print() (SOP) will call the toString method when fed an object.
If you don't overwrite the method toString(), SOP will call the parent toString() which, if parent is the Object class, it will print the hashCode of the object
If you overwrite the method, SOP will call your toString() method
System.out.println(obj) will print the returned string from obj.toString() if you dont override it it will call the base object.toString() method which by default the toString method for class Object returns a string consisting of the name of the class of which the object is an instance, the at-sign character `#', and the unsigned hexadecimal representation of the hash code of the object. In other words, this method returns a string equal to the value of:
getClass().getName() + '#' + Integer.toHexString(hashCode())

Instantiating a class, toString terms

I have two classes :
import android.cla;
public class CW {
public static void main(String [] args){
System.out.println(new cla());
}
}
public class Cl {
#Override
public String toString(){
return "LOL";
}
}
In the first class I'm calling the objects toString() method, which has been overriden and printing it to console. It clearly returns "LOL";
I have two questions :
Is it possible to return data while instantiating like this (new cla()) without overriding the objects toString() method; and
What is the proper term for instantiating classes like this (new cla()), that's without declaration like : Object l = new cla()
Thanks. Please correct me on the proper terms.
1 - No it isn't. A 'constructor' is a special method on the class that always returns an object instance of the class. The whole point of the constructor is to return the object. So no, it can't return anything else.
1a - The reason that System.out.println calls the toString method is because you are asking it to print out that object to the screen, and the toString method is the method chosen by the authors of println (and the Java language in general) to give a string representation of the object.
2 - That way of writing isn't really called anything. It's just an expression that you're passing as an 'actual parameter' to the println method. True, it's an expression that instantiates a new object, but it's no different to println("a string"). You could call it an anonymous object if you really wanted to.
2a - (old answer that doesn't actually answer your question but I'll keep it here) That's just called 'using a less derived reference† to a class'. Beware you can only call methods on the type of the reference, so if you added extra methods to your Cl class you couldn't call them from an Object reference. Look into Liskov substitution principle.
† 'less derived' or 'supertype' or 'superclass' or 'more general class' etc...

Categories