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.
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.
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.
精彩评论