简体   繁体   中英

Override toString method in Java

public class Curiosity {



public void toString()//error because of this specific method name 
{
    System.out.println("method is successfully implemented");
}



}

How can i use a method of the same name "toString()" if i want to ?

Do I have to give its return type as String if not what should i do to change its return type like suppose if i want to use a void return type for toString does java allow that ?

toString() method must return a String . That's the only way to override Object 's toString() .

public String toString()
{
    return "method is successfully implemented";
}

If you wish to use the same name but not override Object 's toString , you can overload the name toString by adding arguments, thus changing the signature of your method.

Example :

public void toString (String something)
{
    System.out.println("method is successfully implemented " + something);
}

You are trying to overload toString() method in a wrong manner

Overloaded methods are differentiated by the number and the type of the arguments passed into the method. In the code sample, draw(String s) and draw(int i) are distinct and unique methods because they require different argument types.

You cannot declare more than one method with the same name and the same number and type of arguments, because the compiler cannot tell them apart.

The compiler does not consider return type when differentiating methods, so you cannot declare two methods with the same signature even if they have a different return type.

The only way to use toString() in your class is by keeping the return type as String

public String toString()
{
   //your code here
}

That is how it is defined in Object class and if you wish to override it you will have to use the exact signature

or if you still wish to use the method name as toString what you can do is change the method's signature.

A method's signature includes method's name and the parameters. Remember that return type is not a part of a method's signature

You can look at the source code of the java.lang.Object .

The toString method have a return value in String type. You can't have another method which's name is toString but return type is not String.

Actually, it's forbidden in Java in any inheritance relationship. When you call the method, the compiler only cares the name and the parameters. So how can it distinguishes the methods of the same name but with the different return type?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM