Method overloading toString() - java

Hi I was just wondering if it is possible to have multiple toString() methods in the same class. The two different toString() methods print different things. ex:
public String toString(){
return String.format("(%.1f%+.1fi)%n", real, imaginary);
}
public String toString(){
return String.format("z=%.3f(cos(%.3f)+isin(%.3f))%n",real,imaginary,imaginary);
}

No, you can't have two methods with the same name and signature.
A "signature" in this case means the number of arguments and their types. Changing this won't allow you to override toString() twice, it'll just make one a normal method.
public String toString(){
return String.format("(%.1f%+.1fi)%n", real, imaginary);
}
public String toString( boolean fubar ){
return String.format("z=%.3f(cos(%.3f)+isin(%.3f))%n",real,imaginary,imaginary);
}
The second method has a different signature, so it's legal, but doesn't override toString().

You can have a toString() method that takes an argument to indicate the expected format of the output.
Say you have 3 formats. You can have an enum and based on the value you get, you print/return the value in that format.
EDIT 1
Let's say you have an enum
public enum PrintFormat{
F1, F2, F3
}
and the toString() method that you're going to overload
public toString(PrintFormat format){
switch(format){
case F1:
//return in a diff format
case F2:
//return in a diff format
//so on so forth
}
}

No, it is not possible to overrides multiple toString() in the same Class

Related

Understanding java compiler

Assuming I have this two classes, in separate files:
public class Text
{
public String _word;
public Text(String w)
{
_word = w;
}
public String getWord()
{
return _word;
}
public boolean equals (Text other)
{
return ((other!=null)&&(_word.equals(other._word)));
}
public boolean test (Text other)
{
return 1==1;
}
}
2nd class:
public class Sentence
{
public String _word;
public Sentence(String w)
{
_word = w;
}
public String getWord()
{
return _word;
}
public boolean equals (Object other)
{
return ((other!=null) && (other instanceof Sentence)
&& (_word.equals(((Sentence) other)._word)));
}
}
And the following main:
public static void main(String[]args){
Text y1 = new Text("abc");
Sentence z1 = new Sentence ("abc");
**
}
Let's say I run the following command where ** is:
System.out.println (y1.equals(z1));
Everything is ok, and it outputs "false".
But, if I run this command:
System.out.println (y1.test(z1));
The compiler screams "Sentence can not be converted to Text".
Two questions:
Why it works for equals but not for test? y1 is Text, so calling y1.equlas() calls to equlas() inside Text, and there it gets only Text as parameter.
If it DOES work, why the output is false? both "_word" set to "abc".
Thanks!
You've defined an equals(Text) method in Text. However, it doesn't override the existing equals(Object) method that it inherits from Object. Because of this, your equals(Text) method overloads the equals(Object) method in Object. Consequently, you can call y1.equals(z1). Because z1 is a Sentence, the equals(Object) method is the one called. The Sentence object matches Object but not Text. The equals method in Object compares object references to see if they're identical.
The equals method for class Object implements the most discriminating possible equivalence relation on objects; that is, for any non-null reference values x and y, this method returns true if and only if x and y refer to the same object (x == y has the value true).
They're not, so it returns false.
You've defined a test(Text) method in Text. There are no other overloads available, and Sentence doesn't match Text at all, so the compiler complains.
Incidentally, the equals(Object) method you've defined in Sentence is a proper override of equals, checking for null and the class of the argument.
According to the Object class definition, you inherit this in all classes
public boolean equals(Object obj)
In your case y1.equals(z1) is actually executed as y1.equals( (Object) z1), a valid cast since all objects inherit Object. You then have the above method called.
I think in Text.java you wanted to override Object.equals(Object other), but instead of overriding you created an other method with the same name (equals(Text other)), but with different parameter type.
That is why System.out.println (y1.equals(z1)); compiles: that equals call matches the signature equals(Object), which method Text inherits from Object.
On the other hand, System.out.println (y1.test(z1)); fails to compile, since Text has only 1 method with the name test, and its formal parameter type is Text, which doesn't match the type of the actual parameter (Sentence).

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

Overload or Override int method() for toString() formatted output?

I have a class that stores a number in the millions. What I would like to do is override the method to get that number and apply a string formatter for readable UIX output.
This is what I have to "overload" the to gets:
class dudViewModel {
public int gettotal () {
return this.total;
}
public String gettotal(String formated) {
return String.format("%.1f", (float)total / 1000000);
}
}
So it's the difference between the two following calls:
gettotal(); // returns 23,400,000
and
gettotal("formatted"); // returns 23.4
Is there a better way or pattern in java to overload an individual method() that returns a number and override i with a tostring() call somehow to overide default number return and instead return a formatted string?
I think the best way is to separate the presentation from the business logic. In this approach, you'd just have a single getTotal() method returning int. A completely separate method of a separate class would take that int and format it for the UI.
or patter in java to overload an individual method() that returns a number and override i with a tostring()
You can apply Decorator pattern which allows behavior to be added to an individual object, either statically or dynamically, without affecting the behavior of other objects from the same class
What a method does, must be indicated in its name. In this case, the two methods should be named different rather than trying to overload, overloading should alter the processing, not the total effect or output.
class dud {
public int getTotal () {return this.total;}
public String getFormattedTotal() {return String.format("%.1f", (float)total / 1000000);}
public String getFormattedTotal(String customFormat) {return String.format(customFormat, (float)total / 1000000);}
}
Separate the data from its representation and you can also test it in isolation.
class Dud {
public int getTotal () {return this.total;}
}
class DudPresentation {
private Dud dud;
public DudPresentation(Dud dud){
this.dud = dud;
}
public String getTotal() {
return getTotal("%.1f");
}
public String getTotal(String format) {
int total = dud.getTotal();
return String.format(format, (float)total / 1000000);
}
}

Override of toString() that makes use of the overridden toString()

Basically this is what I am trying to achieve.
classname#address(?)[original toString()], object's name, object's age
#Override public String toString()
{
return String.format("%s , %s , %d", this.toString(), this.getName(),this.getAge());
}
Problem, toString() gets called recursively.
I can't call super.toString() because that's not what I want. I want 'this' to call the original toString().
This
this.super.toString()
doesn't work for obvious reasons.
I'm running out of steam, can this be done once a method gets overridden? I.e. call the original implementation ?
(my edit) Basically what I need is: override toString to display two properties of 'this' object, and I also want to have 'this' call the original toString.
This is not a project , or work. Just playing(learning) with Java language. Thanks
You're looking for super.toString().
Actually, I was trying to achieve the same thing, where super.toString() wasn't exactly what I wanted. I believe that this is not possible.
Specifically, I have a domain class in Groovy/Grails, and I wanted to override its toString() method to add some extra information:
class Child extends Parent {
public String toString() {
return super.toString(this) + extra_info // not possible!!!
}
}
This is not identical to return super.toString() + extra_info. In one case I get e.g.
com.example.domain.Parent : 15, extra_info. (Wrong. The instance is the same, but toString includes type information.)
In the other:
com.example.domain.Child : 15, extra_info. (Correct, but not possible.)

toString in subClasses Cannot Override abstract toString , Java

I have this very long exercise and I came a cross a problem in each sub class.
The problem says and I have no idea what mistake I've made while writing.
If you could check the 4 toString methods I would be much apprecaited .
The code is here: http://paste.org/pastebin/view/39488
I know I should past the code here but it is very long and I'm not able to organize it well.
toString() in Shape cannot override toString() in java.lang.Object; attempting to use incompatible return type
toString() in Square cannot override toString() in java.lang.Object; attempting to use incompatible return type
`
toString() in Sphere cannot override toString() in java.lang.Object; attempting to use incompatible return type
toString() in Cube cannot override toString() in java.lang.Object; attempting to use incompatible return type
thanks
You need to change the return type of the function to String and return the text instead of writing it to System.out.
public String toString() {
return "(" + super.getX() + ", " +
super.getY() +") " + "side: " + super.getDimension1();
}
EDIT: If you want to have a method that outputs the object directly to System.out in textual form, you'll need to call it something else than toString(). This is because toString() is a method belonging to java.lang.Object which all Java classes automatically extend.
toString() has to return String not void.
// false
public abstract void toString();
// right
public abstract String toString();
Note: You should not print (System.out) in the toString() method. You should rather return a String represenation of the object.
because you try to override it with a void return type. toString should return a String.
It should return a string and not void.
public abstract String toString()
toString() is implemented in Object class and every class extends it. This method is in every class and we can't have two method with same signature but different return type.
As toString() is already there with return type String, we can't have one more toString() with any other return type.

Categories