Why call super() in a constructor? Why call super() in a constructor? java java

Why call super() in a constructor?


There is an implicit call to super() with no arguments for all classes that have a parent - which is every user defined class in Java - so calling it explicitly is usually not required. However, you may use the call to super() with arguments if the parent's constructor takes parameters, and you wish to specify them. Moreover, if the parent's constructor takes parameters, and it has no default parameter-less constructor, you will need to call super() with argument(s).

An example, where the explicit call to super() gives you some extra control over the title of the frame:

class MyFrame extends JFrame{    public MyFrame() {        super("My Window Title");        ...    }}


A call to your parent class's empty constructor super() is done automatically when you don't do it yourself. That's the reason you've never had to do it in your code. It was done for you.

When your superclass doesn't have a no-arg constructor, the compiler will require you to call super with the appropriate arguments. The compiler will make sure that you instantiate the class correctly. So this is not something you have to worry about too much.

Whether you call super() in your constructor or not, it doesn't affect your ability to call the methods of your parent class.

As a side note, some say that it's generally best to make that call manually for reasons of clarity.


We can access super class elements by using super keyword

Consider we have two classes, Parent class and Child class, with different implementations of method foo. Now in child class if we want to call the method foo of parent class, we can do so by super.foo(); we can also access parent elements by super keyword.

    class parent {    String str="I am parent";    //method of parent Class    public void foo() {        System.out.println("Hello World " + str);    }}class child extends parent {    String str="I am child";    // different foo implementation in child Class    public void foo() {        System.out.println("Hello World "+str);    }    // calling the foo method of parent class    public void parentClassFoo(){        super.foo();    }    // changing the value of str in parent class and calling the foo method of parent class    public void parentClassFooStr(){        super.str="parent string changed";        super.foo();    }}public class Main{        public static void main(String args[]) {            child obj = new child();            obj.foo();            obj.parentClassFoo();            obj.parentClassFooStr();        }    }