Super() in Java

super() in Java

super() calls the parent constructor with no arguments.

It can be used also with arguments. I.e. super(argument1) and it will call the constructor that accepts 1 parameter of the type of argument1 (if exists).

Also it can be used to call methods from the parent. I.e. super.aMethod()

More info and tutorial here

What does super() mean in a constructor?

It calls the parent class's constructor

What's the different between super and super() in java?

Both are used in a subclass as a way to invoke or refer to its superclass.

super() is a method call you make inside a constructor or inside an overridden method to invoke the superclass's constructor or the superclass's overridden method. The super() call can also take arguments in these cases.

Note that since all classes by default at least inherit from Object, you can always call super() inside a constructor (it must be the first statement in the constructor though). This super() call is in fact ordinarily inserted by the compiler into your no-arg constructor by default.

This can get tricky however if the superclass doesn't have a no-arg constructor though, in which case your call to super() will fail without the appropriate args. A no-arg constructor is ordinarily generated by default however so you don't have to worry about it, but it won't be automatically generated if you've explicitly define another constructor with args, so that's when you may need to explicitly define one yourself.

super without the parens on the other hand is simply a reference to the superclass itself, like any other variable. It can be used to invoke any accessible method in that class or to refer to any of the class's accessible fields, just like you would with any other reference. Eg: super.doSomething() or super.x

super() in a constructor of a class without inheritance

Constructors of superclasses are invoked when you create an instance of your class. In case your class extends sth explicitly, there are two options:

  • If the super class has a default constructor, then it's invoked;
  • In case there is no default constructor, you should specify which constructor you invoke and send corresponding arguments for it.

Calling super() without parameters basically means that you invoke a default constructor. It's not necessary, because it will be invoked even if you don't do it explicitly.

Since all the objects in java implicitly extend Object, then the default constructor of Object is invoked all the time you create an instance of the class. super() just makes it explicit. But, why should we add explicitness to something that is quite clear already.

Moreover, that's sometimes added by IDE when you use code generation tools(e.g. Eclipse).

You can read really good description on how consturtors of class/superclass work in a book for OCA preparation: https://www.amazon.com/OCA-Certified-Associate-Programmer-1Z0-808/dp/1118957407



Related Topics



Leave a reply



Submit