In many of Android methods, especially constructors and overridden methods, you should or even must call the parent class method using super(). When you use the Eclipse Source > Override/Implement Methods... you get code from a template with TODO tags like this:
public MyCanvas(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
}
@Override
protected void onDraw(Canvas canvas) {
// TODO Auto-generated method stub
super.onDraw(canvas);
}
I do not understand exacly what the superclass does in each case so I always insert my code at the exact location of the //TODO tags. In the example, I would call super() before my code in the constructor and after my code in onDraw().
Can I always rely on these code insertions locations in the generated code? Is there a simple rule/explanation when to call super()?
This is a good question. Unfortunately, there is no simple rule for this. You need to know what the superclass implementation does. Sometimes (as in View.onDraw()
), the superclass implementation does nothing; calling super() is both harmless and unnecessary. In other cases (such as Activity.onCreate()
) the superclass implementation performs critical operations that must be executed at some point in the subclass's processing. Sometimes what happens when you call super() should come before any processing in the subclass, sometimes at other points. Sometimes you want to completely replace the superclass processing with your own, in which case you don't call super() at all. You have complete freedom to call the superclass version at any point (or even at multiple points) in your subclass's logic.
In constructors, the call to a superclass constructor (if present) must be the first thing in the method. If you don't have one, the compiler automatically inserts a call to the no-argument constructor in the superclass. (If the superclass does not have a no-argument constructor, or if it is not accessible to the subclass, the compiler generates an error.)
If the documentation doesn't provide enough information, then you have to look at the source code. The Android code is available here (Gingerbread release). The API code is under core
.
EDIT The code is no longer available at git.kernel.org. Here are two other places where you can browse the code:
The main code is in the repository Platform > Frameworks > Base
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With