Sam Sam - 6 months ago 9
Java Question

Why calling Java Object Instance executes method of object

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;
}
}

Answer

"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~)