title: Android Fragment OnAttach method
body: <p>I'm new to Android development and have a question about <code>OnAttach(Context context)</code> method. As far as I understand you override <code>OnAttach</code> method in the class that you extend Fragment and what it basically does is it attaches the fragment to the <code>Activity(Context)</code> that gets passed as a parameter. However, in a lot of example codes I've seen on the internet, people create an interface with methods that the main Activity needs to implement and in <code>OnAttach</code> method, they typecast context as the interface for ex)</p>
  
  <pre><code>public class exampleFragment extends Fragment{
  
  exampleFragmentListener activityCommander;
  
  public interface exampleFragmentListener{
      public void someMethod(String top, String bot);
  
  }
  
  @Override
  public void onAttach(Context context) {
      super.onAttach(context);
      try{
          activityCommander = (exampleFragmentListener)context;
  
      }catch(Exception e){
          throw new ClassCastException(context.toString());
  
      }
  }
  </code></pre>
  
  <p>What I don't get is this piece of code :</p>
  
  <pre><code>activityCommander = (exampleFragmentListener)context;
  </code></pre>
  
  <p>What's the purpose of typecasting context as <code>exampleFragmentListener?</code> Why would we typecast our <strong>main activity</strong> to <strong>fragment?</strong> Why can't the main activity just implement the <code>interface/implement</code> interface methods? Thank you in advance. </p>