Eugene
Eugene

Reputation: 60184

Why do I need to define custom constructor?

If I have a class, let's say, extended from DialogFragment and define custom constructor for it, why should I define a default one? If I wouldn't I get the error message if runtime change occurs.

Upvotes: 0

Views: 1108

Answers (2)

HandlerExploit
HandlerExploit

Reputation: 8251

Constructors may contain code that is run when the object is created. It is sort of like setup code that you want done so the object is ready for what it's supposed to do.

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1500215

I suspect the problem is that in Java, the compiler creates a parameterless constructor for you unless you specify one yourself. If something within Android requires a parameterless constructor, then either you need to not declare any constructors yourself or you need to explicitly declare a parameterless one.

From section 8.8.9 of the Java Language Spec:

If a class contains no constructor declarations, then a default constructor that takes no parameters is automatically provided:

  • If the class being declared is the primordial class Object, then the default constructor has an empty body.
  • Otherwise, the default constructor takes no parameters and simply invokes the superclass constructor with no arguments.

Does that make things clear? I don't know enough about Android to know why you need a parameterless constructor, but presumably it's so that instances can be created via reflection without specifying any arguments for constructor parameters.

Upvotes: 3

Related Questions