Search code examples
javaandroidoopinheritanceinstanceof

Activity is an instance of MainFragmentListener, is it true?


I'm wondering, how it is possible.
I have MainActivty and MainFragment with listener: MainFragmentListener.
Of course I implemented this listener as inteface in MainActivity.
Now I'm trying to understand this:

if (context instanceof MainFragmentListener)

It always true, how it is possible ? MainActivity isn't instance of MainFragmentListener.
MainFragmentListener is a just interface, not object!

MainFragment:

@Override
public void onAttach(Context context) {
    super.onAttach(context);
    if (context instanceof MainFragmentListener) {
        mListener = (MainFragment.MainFragmentListener) context;
    } else {
        throw new RuntimeException(context.toString()
                + " must implement OnFragmentInteractionListener");
    }
}

public interface MainFragmentListener {
    void xx();
    void yy();
}

activity:

public class MainActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener,
        MainFragment.MainFragmentListener{  

public void xx(){
     abc
 };
public void yy(){
abc2
 };

}

Solution

  • Activity is higher in the hierarchy than the fragment interface

    So? Assuming that Fragment is assigned to MainActivity, then context instanceof will be true for

    • The class itself - MainActivity.
    • Any interface you defined on that class (regardless where the definition of the interface is written)
      • NavigationView.OnNavigationItemSelectedListener
      • MainFragment.MainFragmentListener

    As well as each class and interface in the hierarchy

    public class AppCompatActivity extends FragmentActivity implements AppCompatCallback, TaskStackBuilder.SupportParentable, ActionBarDrawerToggle.DelegateProvider

    java.lang.Object
       ↳    android.content.Context
           ↳    android.content.ContextWrapper
               ↳    android.view.ContextThemeWrapper
                   ↳    android.app.Activity
                       ↳    android.support.v4.app.FragmentActivity