Aruka J Aruka J - 1 month ago 7
Java Question

Abstract class and polymorphism issue

I am trying to do the following:

public abstract class MyBaseFragment extends Fragment {
private FloatingActionButton fab;

protected void initFab(View contentView, int resourceId) {
fab = (FloatingActionButton) contentView.findViewById(resourceId);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
launchDetailsDialogFragment(new Animal());
}
});
}

private void launchDetailsDialogFragment(Animal animal) {
//...
}
}


The key point here being the line about making a new Animal.

I have various types of Animals -- Cat, Dog, etc. The page about Cats, the page about Dogs, etc, they will all extend MyBaseFragment. So clicking the FloatingActionButton on the Cat page will execute a function that passes in a new Cat() to the DialogFragment where you can edit its details. Same for Dogs. But each details DialogFragment is a little different, since Cats and Dogs have different properties from each other even though they are both Animals.

However I don't know how to apply polymorphism here. Right now all MyBaseFragment knows is that it will make a new Animal, but really I want it to make a new Cat, or a new Dog, etc, depending on where I am extending the base fragment.

How do I do this?

Answer

Just make the called method abstract ad have each concrete class fill in its own implementation

public abstract class MyBaseFragment extends Fragment {
    private FloatingActionButton fab;

    protected void initFab(View contentView, int resourceId) {
        fab = (FloatingActionButton) contentView.findViewById(resourceId);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                launchDetailsDialogFragment();
            }
        });
    }

    protected abstract void launchDetailsDialogFragment();
}