title: Subclassing Button
body: <p>I get a <code>ClassCastException</code> when I tried to extend the <code>Button</code> class after trying to make a <code>MusicButton</code> subclass. I am not trying to override the background, only add a few additional methods. I am sure I extended that class correctly so this must be something specific with interacting with Android UI components. Why is this occurring?</p>
  
  <p>Here is the line where I get the <code>ClassCastException</code>:</p>
  
  <pre><code>bMusic = (MusicButton) findViewById(R.id.musicButton);
  </code></pre>
  
  <p>Here is the MusicButton class:</p>
  
  <pre><code>public class MusicButton extends Button implements MusicObserver {
  MusicService musicService;
  
  public MusicButton(Context context) {
      super(context);
  }
  
  /**
   * Because we use findViewById to obtain view elements, the service instance
   * variable has to be initialized here instead of constructor.
   * 
   * @param service
   */
  public void setMusicService(MusicService musicService) {
      this.musicService = musicService;
      update();
  }
  
  public void update() {
      /** setMusicService should have been called */
      Assert.assertNotNull(musicService);
  
      if (musicService.isMusicPlaying()) {
          this.setText("Stop Music");
      } else {
          this.setText("Play Music");
      }
  }
  
  /**
   * This function does not update the text of the button even though it knows
   * the status of the music player becuase I want all music observers to be
   * updated consistently, regardless if they are the ones forcing the
   * notification to occurr
   */
  public void buttonPressed() {
      Assert.assertNotNull(musicService);
  
      if (musicService.isMusicPlaying()) {
          musicService.pauseMusic();
      } else {
          musicService.playMusic();
      }
  }
  }
  </code></pre>