Yozarian22
Yozarian22

Reputation: 279

Calling super() with no Superclass?

What happens (if anything) when a constructor calls 'super()' without having any superclass besides Object? Like so:

public class foo implements Serializable, Comparable {

  int[] startPoint;

  public foo() {

    super();

    startPoint = {5,9};
  }
}

Edit:

So if this does nothing, why would anyone explicitly write that in code? Would it make any difference if I just delete that line?

Upvotes: 10

Views: 7623

Answers (7)

Marko Topolnik
Marko Topolnik

Reputation: 200138

It is always OK to delete the line super(); from any constructor, and there is nothing particular about the constructors of classes that extend Object. The call of the nullary superclass constructor is always implied, so whether you write it down or not, you always get the exact same semantics.

Note that this means that if you omit a call to the superclass constructor that does something big, like start database connections or the whole GUI, all this will happen whether or not you actually write super();.

Upvotes: 15

Juvanis
Juvanis

Reputation: 25950

super() is the first call in constructor either it is done explicitly or implicitly. (But of course you might need to change parameters to match parent's constructor.)

Your code:

public foo() 
{
    startPoint = {5,9};
}

What compiler sees from the code above:

public foo()
 {
    super();
    startPoint = {5,9};
 }

So super() is invoked whether you put it explicitly in your code or not. Since all classes derive from Object class, you are calling constructor of Object with your super() call because your class doesn't have any intermediate parents.

Upvotes: 8

ChuyAMS
ChuyAMS

Reputation: 500

super() always call to the constructor to Object class if the class doesn't extends from one class.

Class Object is the root of the class hierarchy. Every class has Object as a super class. All objects, including arrays, implement the methods of this class.

Check this link

Upvotes: 1

PaulProgrammer
PaulProgrammer

Reputation: 17620

It calls Object's constructor, which is empty (does nothing).

Upvotes: 1

SLaks
SLaks

Reputation: 887215

That just calls the Object() constructor, just as if you had any other superclass with a constructor that has no parameters.

Upvotes: 2

chollida
chollida

Reputation: 7894

As you stated, there is a super class (Object).

The default object constructor will be called.

Upvotes: 1

Jigar Joshi
Jigar Joshi

Reputation: 240860

There is always a super class called Object, so it will invoke constructor of Object

Upvotes: 7

Related Questions