无法覆盖toString方法

时间:2015-08-14 12:25:45

标签: java android override object-to-string

我写了一个计时器类。我想覆盖其toString方法。但是当我调用toString方法时,它仍然返回超级实现。 (班级的完全限定名称)

这是我的计时器类:

import android.os.Handler;
import android.widget.TextView;

public class Timer implements Comparable<Timer> {
    private Handler handler;
    private boolean paused;
    private TextView text;

    private int minutes;
    private int seconds;

    private final Runnable timerTask = new Runnable () {
        @Override
        public void run() {
            if (!paused) {
                seconds++;
                if (seconds >= 60) {
                    seconds = 0;
                    minutes++;
                }

                text.setText (toString ()); //Here I call the toString
                Timer.this.handler.postDelayed (this, 1000);
            }
        }
    };

    //Here is the toString method, anything wrong?
    @Override
    public String toString () {
        if (Integer.toString (seconds).length () == 1) {
            return minutes + ":0" + seconds;
        } else {
            return minutes + ":" + seconds;
        }
    }

    public void startTimer () {
        paused = false;
        handler.postDelayed (timerTask, 1000);
    }

    public void stopTimer () {
        paused = true;
    }

    public void resetTimer () {
        stopTimer ();
        minutes = 0;
        seconds = 0;
        text.setText (toString ()); //Here is another call
    }

    public Timer (TextView text) {
        this.text = text;
        handler = new Handler ();
    }

    @Override
    public int compareTo(Timer another) {
        int compareMinutes = ((Integer)minutes).compareTo (another.minutes);
        if (compareMinutes != 0) {
            return compareMinutes;
        }
        return ((Integer)seconds).compareTo (another.seconds);
    }
}

我可以看到文本视图的文本是Timer类的完全限定名称。我甚至试过this.toString但它也不起作用。

1 个答案:

答案 0 :(得分:13)

您正在从匿名内部类toString()调用new Runnable() { ... }。这意味着您在的匿名类实例上调用了toString() ,而不是在Timer实例上。我怀疑你在输出中得到$1,表明它是一个匿名的内部类。

尝试:

text.setText(Timer.this.toString());

...以便您在封闭的Timer实例上调用它。

这是一个简短但完整的控制台应用程序,用于演示差异:

class Test
{
    public Test() {
        Runnable r = new Runnable() {
            @Override public void run() {
                System.out.println(toString()); // toString on anonymous class
                System.out.println(Test.this.toString()); // toString on Test
            }
        };
        r.run();
    }

    public static void main(String[] args) {
        new Test();
    }

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

输出:

Test$1@15db9742
Test.toString()