Android: Should I add an empty constructor to a fragment used in ViewPager

android, android-fragments, android-viewpager, constructor, java

Solution

The Java compiler automatically adds a default no-args constructor (which is the "empty constructor" you refer to in the question) to any class that does not feature a constructor.

The following empty class:

public class A {
}

is equivalent to the following class with a no-args constructor with an empty body:

public class A {

    public A() {
    }

}

You are required to explicitly add a no-args constructor only when including another constructor with one or more arguments, because in this case the compiler does not add it for you.

Problem

I'm making a layout, similar to Google play's. I'm using a ViewPager which requires fragments. I'm getting a little confused now because some sites say that a fragment requires an empty constructor, but the example on developer.android.com doesn't contain a constructor. There code is just like this: ``` public static class DemoObjectFragment extends Fragment { public static final String ARG_OBJECT = "object"; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // The last two arguments ensure LayoutParams are inflated // properly. View rootView = inflater.inflate( R.layout.fragment_collection_object, container, false); Bundle args = getArguments(); ((TextView) rootView.findViewById(android.R.id.text1)).setText( Integer.toString(args.getInt(ARG_OBJECT))); return rootView; } } ``` So is it required to include a constructor in a fragment or can I just leave out the constructor?

Original source