why do I need super() in Android? Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of why do I need super() in Android? without wasting too much if your time.

The question is published on by Tutorial Guruji team.

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.

We are here to answer your question about why do I need super() in Android? - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji