I’m new to JAVA and OOP in general. In this very simple code, why I have to call the onCreate method from the superclass? isn’t it inherited from the superclass? I know that a constructor method is not inherited to the child class and if you want to call the constructor you must invoke the superclass. Is super.onCreate a constructor call? Doesn’t the constructor name must be the same with the class name ?
I know this is a silly question and thank you for your responses.
import android.app.Activity;
public class MainActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
}
The implementation is inherited, but you’re overriding it. You need to indicate that you don’t just want to replace the original behaviour – you want to execute that behaviour from the superclass and then extra code.
This isn’t a constructor call – unless you explicitly call the superclass implementation, its code simply won’t be executed. Also unlike constructors, the superclass implementation call doesn’t have to be the first statement of a method. You can call the superclass implementation wherever you like, even multiple times.
Here’s a short but complete example program demonstrating the difference between calling a super method and not:
(It would be entirely feasible for
Sub.method1to callsuper.method2()by the way. You can call a superclass implementation of any method from the subclass.)