Enforcing Super Calls in Android

Mike Gouline
2 min readSep 22, 2016

When writing libraries in Java, it’s not uncommon to create an abstract class with some basic functionality that the user would extend. But how do you ensure that the overridden methods call through to super?

You might have seen this in the Android source: for example, if you try to override onCreate() in an activity without calling through to super.onCreate(), you’ll notice that the IDE complains.

As it turns out, they use support annotations for that and so can you.

@CallSuper Annotation

Let’s say you have a class Animal (as the tradition goes) and it has a method run().

public class Animal {
public void run() {
// Some basic running procedure that applies to all animals
}
}

Now the user implements a Cat and its own way of running.

public class Cat extends Animal {
@Override
public void run() {
// Some specific cat running that misses the base part
}
}

This would compile just fine, even though we forgot to call through to the super implementation.

Here’s how we can fix it — annotate run() with @CallSuper.

public class Animal {
@CallSuper
public void run() {
...
}
}

Now the compiler will complain about the above Cat implementation until we add the super call like so.

public class Cat extends Animal {
@Override
public void run() {
super.run();
...
}
}

Be Warned

The @CallSuper inspection is quite basic and won’t detect if your call to super is hidden inside another method that you’re invoking from the overridden method. So make sure you keep it local.

Moral of the Story

In case you were looking for a moral of this story, here it is: use support annotations! You can still write code without them, but they could save you from stupid mistakes and oversights even before you compile and fall into another debugging session.

--

--