2015-08-14 156 views
5

我写了一个计时器类。我想重写它的toString方法。但是当我调用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,但它也不起作用。

+0

你用丝网印刷价值 “Integer.toString(秒)。长度”。因此“Log.i(”value“,”“+ Integer.toString(seconds).length);” ?? –

回答

13

你从你的匿名内部类 - new Runnable() { ... }打电话给toString()。这意味着你在上调用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()"; 
    } 
} 

输出:

[email protected] 
Test.toString() 
+2

哦,是的!非常感谢你! btw我正在读你的书! – Sweeper