By Mohan


2010-09-22 08:05:29 8 Comments

Is super() used to call the parent constructor? Please explain super().

15 comments

@aioobe 2010-09-22 08:09:27

Source article: Java: Calling super()


Yes. super(...) will invoke the constructor of the super-class.

Illustration:

enter image description here


Stand alone example:

class Animal {
    public Animal(String arg) {
        System.out.println("Constructing an animal: " + arg);
    }
}

class Dog extends Animal {
    public Dog() {
        super("From Dog constructor");
        System.out.println("Constructing a dog.");
    }
}

public class Test {
    public static void main(String[] a) {
        new Dog();
    }
}

Prints:

Constructing an animal: From Dog constructor
Constructing a dog.

@Mohan 2010-09-22 09:39:23

In my base class i overload the constructor with one,two,...arguments in my derived class i use super() without any argu. then what will happen whether it's automatically calls a default constructor of a base class

@aioobe 2010-09-22 09:41:00

Yes. If you call super() it will invoke the constructor of the super-class that takes no arguments. Similarly, it will invoke the 1-argument constructor if you do super(arg1), and so on.

@Mohan 2010-09-22 12:08:42

if there was no constructor without any argu in base class then what happens if derived class calls super().

@aioobe 2010-09-22 12:19:55

Nothing. It will not compile. If you provide a constructor yourself, the automatic/default/no-argument-constructor will not be generated, thus super() will not be a valid call.

@Mark Burleigh 2018-12-27 11:58:52

As stated, inside the default constructor there is an implicit super() called on the first line of the constructor.

This super() automatically calls a chain of constructors starting at the top of the class hierarchy and moves down the hierarchy .

If there were more than two classes in the class hierarchy of the program, the top class default constructor would get called first.

Here is an example of this:

class A {
    A() {
    System.out.println("Constructor A");
    }
}

class B extends A{

    public B() {
    System.out.println("Constructor B");
    }
}

class C extends B{ 

    public C() {
    System.out.println("Constructor C");
    }

    public static void main(String[] args) {
    C c1 = new C();
    }
} 

The above would output:

Constructor A
Constructor B
Constructor C

@SimonGates 2010-09-22 08:12:55

Some facts:

  1. super() is used to call the immediate parent.
  2. super() can be used with instance members, i.e., instance variables and instance methods.
  3. super() can be used within a constructor to call the constructor of the parent class.

OK, now let’s practically implement these points of super().

Check out the difference between program 1 and 2. Here, program 2 proofs our first statement of super() in Java.

Program 1

class Base
{
    int a = 100;
}

class Sup1 extends Base
{
    int a = 200;
    void Show()
    {
        System.out.println(a);
        System.out.println(a);
    }
    public static void main(String[] args)
    {
        new Sup1().Show();
    }
}

Output:

200
200

Now check out program 2 and try to figure out the main difference.

Program 2

class Base
{
    int a = 100;
}

class Sup2 extends Base
{
    int a = 200;
    void Show()
    {
        System.out.println(super.a);
        System.out.println(a);
    }
    public static void main(String[] args)
    {
        new Sup2().Show();
    }
}

Output:

100
200

In program 1, the output was only of the derived class. It couldn't print the variable of neither the base class nor the parent class. But in program 2, we used super() with variable a while printing its output, and instead of printing the value of variable a of the derived class, it printed the value of variable a of the base class. So it proves that super() is used to call the immediate parent.

OK, now check out the difference between program 3 and program 4.

Program 3

class Base
{
    int a = 100;
    void Show()
    {
        System.out.println(a);
    }
}

class Sup3 extends Base
{
    int a = 200;
    void Show()
    {
        System.out.println(a);
    }
    public static void Main(String[] args)
    {
        new Sup3().Show();
    }
}

Output:

200

Here the output is 200. When we called Show(), the Show() function of the derived class was called. But what should we do if we want to call the Show() function of the parent class? Check out program 4 for the solution.

Program 4

class Base
{
    int a = 100;
    void Show()
    {
        System.out.println(a);
    }
}

class Sup4 extends Base
{
    int a = 200;
    void Show()
    {
        super.Show();
        System.out.println(a);
    }
    public static void Main(String[] args)
    {
        new Sup4().Show();
    }
}

Output:

100
200

Here we are getting two outputs, 100 and 200. When the Show() function of the derived class is invoked, it first calls the Show() function of the parent class, because inside the Show() function of the derived class, we called the Show() function of the parent class by putting the super keyword before the function name.

@erikbwork 2010-09-22 08:23:16

Why didn't you indent your sourcecode examples? Is there a specific reason?

@Mohan 2010-09-22 09:32:54

NO erikb,I want to know the usage of super().Hereafter only i going to

@Mohan 2010-09-22 09:35:01

In my base class i overload the constructor with one,two,... arguments

@Mohan 2010-09-22 09:36:58

but in my derived class i use super() without any argu. then what will happen whether it's automatically calls a default constructor of a base class

@user207421 2017-06-23 10:06:14

super() is not a keyword. It is a constructor invocation. super is a keyword, and #1 and #2 only makes sense with that definition.

@Pritam Banerjee 2017-06-18 03:17:49

I have seen all the answers. But everyone forgot to mention one very important point:

super() should be called or used in the first line of the constructor.

@otoloye 2017-04-21 09:06:52

super is a keyword. It is used inside a sub-class method definition to call a method defined in the superclass. Private methods of the superclass cannot be called. Only public and protected methods can be called by the super keyword. It is also used by class constructors to invoke constructors of its parent class.

Check here for further explanation.

@Roland Illig 2016-12-11 10:53:11

Calling the no-arguments super constructor is just a waste of screen space and programmer time. The compiler generates exactly the same code, whether you write it or not.

class Explicit() {
    Explicit() {
        super();
    }
}

class Implicit {
    Implicit() {
    }
}

@iprashant 2017-05-30 06:05:38

I found it used in few classes, not sure what was the purpose. Your answer is helpful.

@hitesh kumar 2015-10-21 16:31:38

Super keyword in java

Super keyword is a reference variable that is used for refer parent class object.

Why use super keyword in java ?

Whenever inherit base class data into derived class it is chance to get ambiguity, because may be base class and derived class data are same so to difference these data need to use super keyword

Super keyword at method level ?

Super keyword is also used to call parent class method. Super keyword should be use in case of method overriding.

When use Super keyword at method level ?

Super keyword use when base class method name and derived class method name have same name.

http://www.tutorial4us.com/java/java-super-keyword

@user207421 2017-06-23 10:08:15

It is not a reference variable, and the proof is that super() is valid. If it was a reference variable that would not be valid. It is a keyword with more than one possible use.

@Todd Zhang 2015-07-14 01:27:28

For example, in selenium automation, you have a PageObject which can use its parent's constructor like this:

public class DeveloperSteps extends ScenarioSteps {

public DeveloperSteps(Pages pages) {
    super(pages);
}........

@WIll 2015-05-03 19:01:12

Just super(); alone will call the default constructor, if it exists of a class's superclass. But you must explicitly write the default constructor yourself. If you don't a Java will generate one for you with no implementations, save super(); , referring to the universal Superclass Object, and you can't call it in a subclass.

public class Alien{
   public Alien(){ //Default constructor is written out by user
   /** Implementation not shown…**/
   }
}

public class WeirdAlien extends Alien{
   public WeirdAlien(){
   super(); //calls the default constructor in Alien.
   }

}

@user207421 2017-06-23 10:06:59

With no arguments.

@Luchnik 2015-02-02 13:19:36

The super keyword can be used to call the superclass constructor and to refer to a member of the superclass

When you call super() with the right arguments, we actually call the constructor Box, which initializes variables width, height and depth, referred to it by using the values of the corresponding parameters. You only remains to initialize its value added weight. If necessary, you can do now class variables Box as private. Put down in the fields of the Box class private modifier and make sure that you can access them without any problems.

At the superclass can be several overloaded versions constructors, so you can call the method super() with different parameters. The program will perform the constructor that matches the specified arguments.

public class Box {

    int width;
    int height;
    int depth;

    Box(int w, int h, int d) {
        width = w;
        height = h;
        depth = d;
    }

    public static void main(String[] args){
        HeavyBox heavy = new HeavyBox(12, 32, 23, 13);
    }

}

class HeavyBox extends Box {

    int weight;

    HeavyBox(int w, int h, int d, int m) {

        //call the superclass constructor
        super(w, h, d);
        weight = m;
    }

}

@pakore 2010-09-22 08:09:24

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

@KNU 2014-08-06 10:01:44

NOTE: in first case, parent class must have a no argument constructor failing to which will throw compilation error.

@aioobe 2015-12-22 14:59:56

Nit: The parent/child terminology isn't very good for class hierarchies. (A child is not a father.)

@Aaron Franke 2017-12-12 00:13:35

Are there any restrictions on where super can be used?

@Vivek Chavda 2017-12-15 21:48:12

@aioobe A child (a son or daughter of any age) can be a parent. Works fine for hierarchies (especially when multiple inheritance is not supported)

@Vivek Chavda 2017-12-15 21:49:57

@AaronFranke One restriction would be trying to call its static methods without instantiating the calling class - stackoverflow.com/questions/14112792/…

@aioobe 2017-12-16 13:50:41

@VivekChavda, sure a child can be a parent, just like a student can be a teacher, etc. But I think you understand the difference compared to Animal -> Dog for instance. A Dog is necessarily an Animal. Parent/child is typically a has a relationship ("A parent has a child") while an Animal/dog is an "is a" relationship. See aioo.be/2016/06/29/a-child-is-not-always-a-parent.html

@aioobe 2017-12-16 13:56:39

@AaronFranke, "Are there any restrictions on where super can be used?" -- Yes, super(...) may only be used as the first statement in a constructor.

@Vivek Chavda 2017-12-19 18:05:44

Oh I see what you're saying. Yeah, 'super' and 'sub' definitely seem more precise

@Heinzi 2010-09-22 08:08:21

Is super() is used to call the parent constructor?

Yes.

Pls explain about Super().

super() is a special use of the super keyword where you call a parameterless parent constructor. In general, the super keyword can be used to call overridden methods, access hidden fields or invoke a superclass's constructor.

Here's the official tutorial

@Sean Patrick Floyd 2010-09-22 08:12:03

super() is used to call the parent constructor, super.myMethod() is used to call an overridden method.

@atamanroman 2010-09-22 08:22:48

@seanizer or any other method of the superclass (including statics) if its in scope. super is just a reference to your base class.

@Dheeraj Joshi 2010-09-22 08:34:49

I don't think super() is used to call base class methods. You can use super.method() though.

@Heinzi 2010-09-22 08:40:52

@seanizer, @Dheeraj: Thanks for your feedback, I've adapted my answer.

@Olathe 2010-10-03 21:51:37

Constructors
In a constructor, you can use it without a dot to call another constructor. super calls a constructor in the superclass; this calls a constructor in this class :

public MyClass(int a) {
  this(a, 5);  // Here, I call another one of this class's constructors.
}

public MyClass(int a, int b) {
  super(a, b);  // Then, I call one of the superclass's constructors.
}

super is useful if the superclass needs to initialize itself. this is useful to allow you to write all the hard initialization code only once in one of the constructors and to call it from all the other, much easier-to-write constructors.

Methods
In any method, you can use it with a dot to call another method. super.method() calls a method in the superclass; this.method() calls a method in this class :

public String toString() {
  int    hp   = this.hitpoints();  // Calls the hitpoints method in this class
                                   //   for this object.
  String name = super.name();      // Calls the name method in the superclass
                                   //   for this object.

  return "[" + name + ": " + hp + " HP]";
}

super is useful in a certain scenario: if your class has the same method as your superclass, Java will assume you want the one in your class; super allows you to ask for the superclass's method instead. this is useful only as a way to make your code more readable.

@Sagar V 2010-09-22 08:10:44

That is correct. Super is used to call the parent constructor. So suppose you have a code block like so

class A{
    int n;
    public A(int x){
        n = x;
    }
}

class B extends A{
    int m;
    public B(int x, int y){
        super(x);
        m = y;
    }
}

Then you can assign a value to the member variable n.

@Bozho 2010-09-22 08:09:00

Yes, super() (lowercase) calls a constructor of the parent class. You can include arguments: super(foo, bar)

There is also a super keyword, that you can use in methods to invoke a method of the superclass

A quick google for "Java super" results in this

Related Questions

Sponsored Content

14 Answered Questions

[SOLVED] Comparing Java enum members: == or equals()?

  • 2009-11-17 17:26:27
  • Matt Ball
  • 619756 View
  • 1625 Score
  • 14 Answer
  • Tags:   java enums

85 Answered Questions

[SOLVED] Is Java "pass-by-reference" or "pass-by-value"?

65 Answered Questions

[SOLVED] How do I generate random integers within a specific range in Java?

  • 2008-12-12 18:20:57
  • user42155
  • 3899665 View
  • 3359 Score
  • 65 Answer
  • Tags:   java random integer

55 Answered Questions

[SOLVED] Creating a memory leak with Java

57 Answered Questions

[SOLVED] How do I read / convert an InputStream into a String in Java?

7 Answered Questions

[SOLVED] Understanding Python super() with __init__() methods

21 Answered Questions

[SOLVED] How do I call one constructor from another in Java?

  • 2008-11-12 20:10:19
  • ashokgelal
  • 805136 View
  • 2131 Score
  • 21 Answer
  • Tags:   java constructor

19 Answered Questions

[SOLVED] Why do this() and super() have to be the first statement in a constructor?

  • 2009-07-22 21:25:15
  • Joe Daley
  • 211673 View
  • 569 Score
  • 19 Answer
  • Tags:   java constructor

11 Answered Questions

[SOLVED] Proper use cases for Android UserManager.isUserAGoat()?

30 Answered Questions

[SOLVED] How to avoid Java code in JSP files?

  • 2010-07-05 07:24:06
  • chmoelders
  • 276146 View
  • 1643 Score
  • 30 Answer
  • Tags:   java jsp scriptlet

Sponsored Content