Why super() is used in Constructor?

117 views Asked by At

I was learning about custom ArrayAdapter.Found this project on Github. I can't figure out why super is used here.

public AndroidFlavorAdapter(Activity context, ArrayList<AndroidFlavor>Flavors) {

        super(context, 0, Flavors);
  }

When I remove super this error pops up.

X There is no applicable constructor to '()’

Any help?

2

There are 2 answers

0
Stephen C On

Every constructor needs to another constructor as the first thing it does1. There are three ways to do this:

  • A constructor can make an explicit super call, either with or without parameters. The parameters types need to match the signature of a constructor declared in the superclass.

  • A constructor can make an explicit this call. This calls another constructor declared by this class.

  • If there no explicit super or this class, an implicit super() call is added to the constructor by the Java compiler. For this to work, there needs to be a constructor in the superclass with no arguments; i.e. a no-args constructor.

1 - Except for java.lang.Object which has no superclass. Note that the bytecode verifier checks this. If you use (say) a bytecode assembler to create a class with a constructor that doesn't call a superclass constructor, it will be rejected by the classloader.


So ...

Why super(...) is used in Constructor?

To explicitly call a superclass constructor. Notice that in this case you are passing arguments to the superclass constructor.

When I remove super this error pops up: "There is no applicable constructor to '()’"

That is because the compiler cannot find the superclasses no-args constructor that is implicitly invoked if you don't have an explicit super(...) call.

Can you please tell me why the second parameter in super is 0.

The javadocs for the superclass should explain what that means. In this case, the 2nd parameter is a Resource ID. I'm not sure that it makes sense, but I've seen it said that Resource ID 0 means null.

0
omt66 On

Because the base class is probably doing the required initialization for the instance.