2

Recently I came across the statement in the Fragment docs:

All subclasses of Fragment must include a public no-argument constructor. The framework will often re-instantiate a fragment class when needed, in particular during state restore, and needs to be able to find this constructor to instantiate it. If the no-argument constructor is not available, a runtime exception will occur in some cases during state restore.

In this regard, I have already read the following posts:

1. Explicitly writing default empty constructor.

2. Default constructors and inheritance in Java.

3. Java entity - why do I need an empty constructor?.

4. Do fragments really need an empty constructor?.

If I recall correctly, Java automatically provides a default empty constructor when no constructor is defined (as is the case with Fragments), so why do we need to define one anyway ? What purpose does this serve ? And what difference does it make if we don't define a default constructor in a Fragment ?

Community
  • 1
  • 1
Yash Sampat
  • 30,051
  • 12
  • 94
  • 120
  • 3
    There should be no problem. The paragraph should rather read "don't use non empty constructors with fragments". If you don't have an explicit empty constructor, the super constructor will be used. Just don't use non empty constructors :) – ElDuderino May 22 '14 at 13:26
  • @ElDuderino right on! The way the documentation frames it is misleading. – Abhijit Oct 04 '14 at 21:01

2 Answers2

2

Java automatically provides a default empty constructor when no constructor is defined (as is the case with Fragments)

Yes it does, but if you have a parametric constructor then it doesn't.

But in the case of fragments, the FragmentManagerImpl recreates then with reflection using the default constructor after process death (low memory condition), so any parameters you would provide instead of using the arguments bundle will be nulled out.

EpicPandaForce
  • 79,669
  • 27
  • 256
  • 428
0

If you do not define any constructors you will have the default public empty constructor and it is just what you need. No need to define it explicitly. But if you create a non-empty constructor (which is not a widely used practice) you should also always define public empty constructor that will be used by the system when the fragment will be recreated.

TpoM6oH
  • 8,385
  • 3
  • 40
  • 72