What does super() method do?
What 开发者_如何学Pythondoes the super method do?
public DataFetch(Context context) {
super();
this.ctx = context;
}
Does this constructor make the context of the newly created object the context of the super class? Not 100% sure how this works. So would the super()
method essentially just be saying "put me into super class mode" to say it in lay man's terms?
It says "initialize my parent class before you initialize me" by calling its default constructor.
super()
calls the parent's class constructor (all the way back to Object) and it runs before the current class's constructor.
There is no such thing as "superclass context" the context is an interface to access information from the application environment like image resources, system services ect. The context will be from whatever you pass in and is class independent. For instance, an Activity
is the implementation of the Context interface you are likely to be using and any view you make from within that activity will have the same Context which is actually that provided by the activity.
When used in a constructor, the super()
keyword appears alone and must be used before the this
keyword can be used. The this
keyword may then be used to call functions on a parent object.
The super() is essential when the parent class constructor takes any parameter
The super() is not necessary when the parent class constructor takes no parameter because super() will be already specified implicitly.
Look at the code:
public class A{
int a;
A(int a){
this.a=a;
//Constructor of parent class which requires a parameter
}
}
public class B extends A{
int b;
B(int a, int b){
super(a);
this.b=b;
//here super(a) is used to pass the parameter required by the
constructor of the parent class A.
}
}
In other words, whenever you create an object for the child class. First, the constructor of the parent class will be called followed by the constructor of the child class. So it is necessary to pass the parameters required by the parent class constructor from the child class constructor using super() method.
Hope it helps!
Please don't forget to upvote
精彩评论