why do I need super() in Android?

From a Activity I am passing data to:

public FoodAdapter(BaseActivity activity, int ResoruceId, ArrayList <food> cake) {


}

However this gives me a error. To fix this I need super() with activity, ResoruceId and cake inside of it. Why do I need to have this super() and what does it do??

Thanks

Answer

It initializes the superclass you’ve extended. You need to do that, because the superclass must be initialized prior to any other code in your constructor running, because subclasses are allowed to access their superclass’s state, and the superclass must have a chance to set up that state. And in general, just as your class has a chance to do initialization (in your constructor), the superclass needs a chance to do it as well.

If the superclass only defines constructors with arguments, you must call the superclass constructor explicitly (with super), passing in those arguments. So if it needs the activity and resource ID, then:

super(activity, ResoruceId); // I would change that second name!

If the superclass defines a constructor with no arguments, and you don’t put a call to super(...) in your constructor, the Java compiler will insert one for you calling the no-args version (e.g., it inserts super(); at the top of your constructor). But it can’t do that if the superclass doesn’t define a zero-args constructor.

I suggest reading up on the basics of inheritance in Java. Oracle has an inheritance tutorial, including this bit about using super.

Leave a Reply

Your email address will not be published. Required fields are marked *