LoveLovelyJava one LoveLovelyJava one - 3 months ago 9
Java Question

overriding toString class does not work

i am trying to use the code below to override

toString
method but I fail. Please tell me why the code does not work not just the way that it will work. Thanks

public class test2 {

public static void main(String[] args) {
String s= "aaa";
System.out.println(s.toString());
}

@Override
public String toString() {

return "bbb";
}
}


output:

aaa

Answer

I'm pretty sure you tried to write something like the following:

public class test2 {

    public static void main(String[] args) {
        test2 t = new test2();
        System.out.println(t.toString()); // shows "bbb"

        String s = "aaa";
        System.out.println(s); // shows "aaa"
        System.out.println(s.toString()); // also shows "aaa"

        Object o1 = new test2();
        System.out.println(o1.toString()); // shows "bbb" because test2 overrides Object's toString()
    }

    @Override
    public String toString() {
        return "bbb";
    }
}

This will use test2's toString() method, which overrides Object' toString() method, as t is of type test2, which inherits from Object.

What you did was to create a String (String a = "aaa") and printing out that string using String's toString() method.