Should super() be the first method call in constructors, if yes why? What can go wrong if this were not the case? Explain with example.
super() is a keyword in java which is used to refer to immediate parent class object. We can use super keyword to call parent class constructor as well as to call parent class method. Super should always be the first statement in the constructor. Because if we call subclass constructor then it is necessary to call superclass constructor first. Super class constructor will basically prepare the ground for the sub-class object in memory.
Java implicitly provides the super method if we don’t write it. But if we write it and this is not the first statement then compilation error will be there stating that “Constructor call must be the first statement”.
For example:
public class A { public A(int z) { System.out.println(z); } public void display() { System.out.println("Hello"); } } public class B extends A { public B(int x, int y) { int z = x + y; display(); //Gives error because superclass object not yet constructed super(z); } public static void main(String args[]) { B b1 = new B(5, 4); } }
Correct code will be :
public class A { public A(int z) { System.out.println(z); } public void display() { System.out.println("Hello"); } } public class B extends A { public B(int x, int y) { super(x + y); display(); } public static void main(String args[]) { B b1 = new B(5, 4); } }
Webner Solutions is a Software Development company focused on developing CRM apps (Salesforce, Zoho), LMS Apps (Moodle/Totara), Websites and Mobile apps. If you need Web development or any other software development assistance please contact us at webdevelopment@webners.com